jQuery check if element has a class beginning with some string

前端 未结 6 1981
面向向阳花
面向向阳花 2021-02-02 00:52

I need to loop through some elements in the page and then, for each one, if it had a class beginning with, for example, \"C\", do something.

$(\'#dialog li\').e         


        
6条回答
  •  花落未央
    2021-02-02 01:07

    Carefull with $('#dialog li[class^="C"]')! It will only match elements, whose class attribute starts with "C" not ones with a class starting with C. For example it will not match

  • .

    AFAIK what you want is not possible mit jQuery alone. You would need to loop through the classes and check each separatly. Something like:

    $('#dialog li').filter(function(){
      var classes = this.className.split(/\s/);
      for (var i = 0, len = classes.length; i < len; i++) 
        if (/^C/.test(classes[i])) return true;
      return false;
    }).each( ... )
    

    Alternativly you should consider changing your approach, and give all elements an additional class and filter by that. This has the addvantage that it can also be used in CSS:

提交回复
热议问题