0

Hello i have set of elements. They have several classes on one element.

 <div class="color1 chaire">&nbsp;</div>
 <div class="color11 chaire">&nbsp;</div>
 <div class="color1 chaire">&nbsp;</div>
 <div class="color12 chaire">&nbsp;</div>
 <div class="color2 chaire">&nbsp;</div>
 <div class="color2 chaire">&nbsp;</div>
 <div class="color2 chaire">&nbsp;</div>
 <div class="color2 chaire">&nbsp;</div>
 <div class="color23 chaire">&nbsp;</div>
 <div class="color23 chaire">&nbsp;</div>
 <div class="color3 chaire">&nbsp;</div>
 <div class="color3 chaire">&nbsp;</div>
 <div class="color3 chaire">&nbsp;</div>
 <div class="color3 chaire">&nbsp;</div>
 <div class="color4 chaire">&nbsp;</div>

I want to count how much each colorX divs are?

I need structure like:

color1 : 2
color2 : 4
color3 : 4
color4 : 1
color11 : 1
color12 : 1
color23 : 2

I write code:

function countvalues(a) {
    var b = {}, i = a.length, j;

    while( i-- ) {
      j = b[a[i]];
      b[a[i]] = j ? j+1 : 1;
    }
    return b;
}

var coalition = new Array();    
var elements = $(".chaire").not(".notactive");
    elements.each(function () {
       var  class = $(this).attr("class");
       class = class.substring(0, class.indexOf(" "));
       coalition.push(class);
 });

   b = countvalues(coalition);

Perhaps there is easier way to do this?

2 Answers 2

1
$("div[class^=color]").size();
Sign up to request clarification or add additional context in comments.

2 Comments

Yes i can change elements = $(".chaire").not(".notactive"); with $("div[class^=color]"); But more?
It may be worth taking a step back on this one and ask if counting classes is really the way to go. Can't imagine why you would want to do this. If you are trying to use the classes to confer information to the page then this is the wrong use of the class element and you may be better using the html5 data- syntax (see ejohn.org/blog/html-5-data-attributes)
1

This should do the trick:

$('div[class^="color"]').length;

2 Comments

Nice one! Using pure jQuery is definitely the best option.
But i need count for each colorX that present in <div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.