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>
In JavaScript, to get the list of classes, you can use
.className.split(' ')
, returns an Array
.classList
, returns a DOMTokenList
In jQuery, you can use .prop()
to get className
or classList
properties.
To iterate them, you can use:
for
loop, e.g. for(var i=0; i<classes.length; ++i)
for...of
loop, e.g. for(var cl of classes)
.forEach
, only for arrays, e.g. classes.forEach(fn)
$.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)
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With