Reputation: 19688
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
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
Reputation: 490163
You could create it...
$.fn.classCount = function() {
return $.grep(this.attr("class").split(/\s+/), $.trim).length;
};
If you don't have jQuery, you could use...
var classLength = element.classList.length;
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;
Upvotes: 5