tags:

views:

153

answers:

1

I have a number of elements on my page that belong to classes with unique identifiers, based on my backend programming. Such that I may have the following:

<element class="element-1"></element>
<element class="element-1"></element>
<element class="element-2"></element>
<element class="element-2"></element>
<element class="element-3"></element>
<element class="element-3"></element>

Is there a way I can count the unique occurrences of these classnames with jQuery, so that whatever function would do that would return 3?

A: 
var obj = {};
var num = 0;
$("element[class^=element]").each(function() {
  var cl = $(this).attr("class");
  if(!obj[cl]) {
    obj[cl] = {};
    num++;
  }
});
alert(num);
Josh Stodola
Awesome, thanks!
neezer
I've read the jQuery documentation, still can't understand why that works?
MeLight