jQuery check if element has a class beginning with some string

前端 未结 6 2051
面向向阳花
面向向阳花 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:11

    You can try that selector. That will work if there are two or more classes like this "Clown foo doo" and

    You can try however something like this $('#dialog li[class*="C"]') in which case will select anything that include the "C" letter, for excample "exCelence foo".

    If you are interested in counting how many classes start with "C" no matter of their position (no matter if they are at the beginning, at the and or somewhere in the middle) then you can try something like this:

    $('#dialog li[class^="C"]').each(function() {
      var classes = div.attr("class").split(" "); 
      var count = 0; 
      $.each(classes, function(i, v){ if(v.indexOf('C')!=-1) count++; });
      if (count == 1)   alert("It has one 'C' class");
      if (count>1) alert("It more than one 'C' class");
    }
    

提交回复
热议问题