chris Frisina
chris Frisina

Reputation: 19688

Count the number of classes an element has?

If you were to label elements by some [tag] system, likely attached by the user, and you wanted to count the number of tags (defined by the number of classes the element has), how would you accomplish this?

This could be beneficial if you were to try to review all elements by number of tags. (This likely could be accomplished by other structures, but if you were to only reference the element tags in this way)

Jquery has .hasClass(), is there something like .classCount()

Upvotes: 3

Views: 2984

Answers (3)

Michael
Michael

Reputation: 2993

You can use the classList attribute if you are using HTML5. For example

$("#someElementId").classList.length 

would return 2 for:

<div id="someElementId" class="stinky cheese"></div>

as in http://jsfiddle.net/thegreatmichael/rpdEr/

Upvotes: 1

alex
alex

Reputation: 490163

You could create it...

$.fn.classCount = function() {
    return $.grep(this.attr("class").split(/\s+/), $.trim).length;
};

jsFiddle.

If you don't have jQuery, you could use...

var classLength = element.classList.length;

jsFiddle.

If you don't have jQuery and have to support the older browsers, go with...

var classes = element.className.replace(/^\s+|\s+$/g, "").split(/\s+/);
var classLength = classes[0].length ? classes.length : 0;

jsFiddle.

Upvotes: 5

j08691
j08691

Reputation: 207891

$(element).attr('class').split(/\s+/).length

jsFiddle example

Upvotes: 0

Related Questions