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 acplish this?
This could be beneficial if you were to try to review all elements by number of tags. (This likely could be acplished by other structures, but if you were to only reference the element tags in this way)
Jquery has .hasClass(), is there something like .classCount()
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 acplish this?
This could be beneficial if you were to try to review all elements by number of tags. (This likely could be acplished by other structures, but if you were to only reference the element tags in this way)
Jquery has .hasClass(), is there something like .classCount()
Share Improve this question edited Nov 8, 2012 at 4:08 Michael 2,9931 gold badge29 silver badges68 bronze badges asked Nov 8, 2012 at 3:49 chris Frisinachris Frisina 19.3k23 gold badges91 silver badges172 bronze badges 2- the question i will ask before answering is, how did you try this? – itachi Commented Nov 8, 2012 at 3:51
- trying to think of ways to review elements by the count of classes (again assuming that the classes mean user feedback). And, trying to avoid functions, but i would use one. – chris Frisina Commented Nov 8, 2012 at 3:53
3 Answers
Reset to default 5You 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.
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/thegreatmichael/rpdEr/
$(element).attr('class').split(/\s+/).length
jsFiddle example