admin管理员组文章数量:1431435
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
本文标签: javascriptCount the number of classes an element hasStack Overflow
版权声明:本文标题:javascript - Count the number of classes an element has? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745538061a2662363.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论