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
|
2 Answers
Reset to default 19In JavaScript, to get the list of classes, you can use
.className.split(' ')
, returns anArray
- (HTML5)
.classList
, returns aDOMTokenList
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);
});
$('div').prop('className').split(' ').forEach(fn)
? – Ram Commented Jun 19, 2014 at 1:13element.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