最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - iterate through classes on same element - Stack Overflow

programmeradmin4浏览0评论

If I have a div which has multiple classes assigned to the class attribute, is it possible to iterate through them using the each() function in jQuery?

<div class="class1 differentclassname anotherclassname"><div>

If I have a div which has multiple classes assigned to the class attribute, is it possible to iterate through them using the each() function in jQuery?

<div class="class1 differentclassname anotherclassname"><div>
Share Improve this question asked Jun 19, 2014 at 1:11 Curtis CreweCurtis Crewe 4,3366 gold badges28 silver badges32 bronze badges 5
  • 3 Something like $('div').prop('className').split(' ').forEach(fn)? – Ram Commented Jun 19, 2014 at 1:13
  • @undefined I've updated my question as I forgot to state that I don't know the class names that'll be used as they're placed dynmacially – Curtis Crewe Commented Jun 19, 2014 at 1:14
  • @CurtisCrewe - That shouldn't affect what undefined said (you're splitting the className property, and then forEaching through the list. Should work fine (even if you don't know the class names before) – Jack Commented Jun 19, 2014 at 1:15
  • 1 Why do you need jQuery? element.className.split(' ').forEach(...) will work in every browser that supports forEach, and it's easy to polyfill those that don't. – RobG Commented Jun 19, 2014 at 1:23
  • Possible duplicate of Get class list for element with jQuery – Bob Stein Commented Jan 27, 2018 at 22:24
Add a comment  | 

2 Answers 2

Reset to default 19

In JavaScript, to get the list of classes, you can use

  • .className.split(' '), returns an Array
  • (HTML5) .classList, returns a DOMTokenList

In jQuery, you can use .prop() to get className or classList properties.

To iterate them, you can use:

  • A for loop, e.g. for(var i=0; i<classes.length; ++i)
  • (ES6) A for...of loop, e.g. for(var cl of classes).
  • (ES5) forEach, only for arrays, e.g. classes.forEach(fn)
  • (jQuery) $.each, e.g. $.each(classes, fn)

If you use classList but want to iterate using forEach, you can convert the DOMTokenList into an Array using

  • [].slice.call(classes)
  • (ES6) Array.from(classes)

First you need to get an string that contains the classes with:

$('div').attr('class');

and split it with blank spaces to get an array with:

$('div).attr('class').split(' ');

and then use that array as the first argument to an $.each function where the index and the value can help you to handle it independently

$.each($('div').attr('class').split(' '), function(index, value) {
    console.log('Class name ' + value);
});
发布评论

评论列表(0)

  1. 暂无评论