Search code examples
jqueryclasswildcardprefix

How do I find class prefix with multiple classes in jquery?


I have span tags with multiple classes:

 <div class="container">
 <span class="otherclass item3">Text</span>
 <span class="otherclass item1">Blah</span>
 <span class="item2">Stuff</span>
 </div>

I'm interested in counting the number of span elements with the class prefixed with 'item'. I know that I can do this:

 $(document).on('click','span',function(){
 var ItemTot = $(this).closest('.container').find('[class*= item]').length;
 alert(ItemTot);
 }

... to count the number of span elements with multiple classes, but that won't count the single class span. I can get that with the code below, but surely there is a cleaner way of getting counting both cases?

 .find('[class^=item]').length;

Solution

  • CSS lacks a "word starts with" attribute selector. (It has attribute starts with [^=], and it has word matching [~=], but not a combination of them that matches the start of a word.)

    So you have to do it manually: Live Copy | Live Source

    var ItemTot = $(this).closest('.container').find('[class*=item]').filter(function() {
        return this.className.match(/\bitem/);
    }).length;
    

    That finds any element whose class attribute contains item (anywhere), and then filters based on only those where item is the beginning of a word.