jQuery selector to target any class name (of multiple present) starting with a prefix?

前端 未结 4 1348
栀梦
栀梦 2020-12-02 19:30

I\'m considering one selection statement that would target one of many css class names in a single class attribute value based on a string prefix.

For example, I wan

相关标签:
4条回答
  • 2020-12-02 19:55

    Because of the way the class attribute is designed, you'll need to make use of at least two other attribute selectors (notice the whitespace in [class*=" detail-"]):

    $('a[class^="detail-"], a[class*=" detail-"]');
    

    This selects <a> elements with a class attribute that

    • starts with detail-, or
    • contains a class prefixed with detail-. Class names are separated by whitespace per the HTML spec, hence the significant space character.

    If you'd like to turn this into a custom selector expression, you can do this:

    $.expr[':']['class-prefix'] = function(elem, index, match) {
        var prefix = match[3];
    
        if (!prefix)
            return true;
    
        var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]';
        return $(elem).is(sel);
    };
    

    Then select it like this:

    $('a:class-prefix(detail-)');
    

    Or if you'd like to place this in a plugin:

    $.fn.filterClassPrefix = function(prefix) {
        if (!prefix)
            return this;
    
        var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]';
        return this.filter(sel);
    };
    

    Then call it like this:

    $('a').filterClassPrefix('detail-');
    
    0 讨论(0)
  • 2020-12-02 20:03

    try wildcard selector

    http://www.emadibrahim.com/2009/07/25/jquery-wildcard-selector/

    0 讨论(0)
  • 2020-12-02 20:10

    You could also write a small plugin that uses .map() to walk through the classes.

    $.fn.classBeginsWith = function(str){
      return !str ? this : this.filter( function(){
        return $.map(this.className.split(' '), function(e,i){
          if (e.match(new RegExp('^' + str, 'ig'))) return 1;
        }).length;
      });
    }
    

    And then:

    $('a').classBeginsWith('detail-')
    
    0 讨论(0)
  • 2020-12-02 20:13

    You can add your own selectors, in your case you could add a regular expression selector for attributes:

    http://james.padolsey.com/javascript/regex-selector-for-jquery/

    Then you could do something like this:

    $(':regex(class,(^| )detail-)')
    

    http://jsfiddle.net/ambiguous/ArtRS/1/

    I came across that article somewhere on SO but I can't remember where.

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