jQuery selector regular expressions

前端 未结 10 2281
傲寒
傲寒 2020-11-21 22:36

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.

I have looked for this myself but have

相关标签:
10条回答
  • 2020-11-21 23:09
    $("input[name='option[colour]'] :checked ")
    
    0 讨论(0)
  • 2020-11-21 23:10

    You can use the filter function to apply more complicated regex matching.

    Here's an example which would just match the first three divs:

    $('div')
      .filter(function() {
        return this.id.match(/abc+d/);
      })
      .html("Matched!");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="abcd">Not matched</div>
    <div id="abccd">Not matched</div>
    <div id="abcccd">Not matched</div>
    <div id="abd">Not matched</div>

    0 讨论(0)
  • 2020-11-21 23:12

    Add a jQuery function,

    (function($){
        $.fn.regex = function(pattern, fn, fn_a){
            var fn = fn || $.fn.text;
            return this.filter(function() {
                return pattern.test(fn.apply($(this), fn_a));
            });
        };
    })(jQuery);
    

    Then,

    $('span').regex(/Sent/)
    

    will select all span elements with text matches /Sent/.

    $('span').regex(/tooltip.year/, $.fn.attr, ['class'])
    

    will select all span elements with their classes match /tooltip.year/.

    0 讨论(0)
  • 2020-11-21 23:16

    James Padolsey created a wonderful filter that allows regex to be used for selection.

    Say you have the following div:

    <div class="asdf">
    

    Padolsey's :regex filter can select it like so:

    $("div:regex(class, .*sd.*)")
    

    Also, check the official documentation on selectors.

    0 讨论(0)
  • 2020-11-21 23:20

    If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.

    For example if your want to only select div with id starting with "abc", you can use:

    $("div[id^='abc']")
    

    A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/

    0 讨论(0)
  • 2020-11-21 23:20

    I'm just giving my real time example:

    In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

    document.querySelectorAll("[id^='select2-qownerName_select-result']");

    When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

    $("[id^='select2-qownerName_select-result']")

    0 讨论(0)
提交回复
热议问题