javascript - Count the number of classes an element has? - Stack Overflow

If you were to label elements by some [tag] system, likely attached by the user, and you wanted to coun

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
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745538061a4631997.html

相关推荐

  • javascript - Count the number of classes an element has? - Stack Overflow

    If you were to label elements by some [tag] system, likely attached by the user, and you wanted to coun

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信