Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
ex.
Why has no one simply listed.
$(element).attr("class").split(/\s+/);
EDIT: Split on /\s+/
instead of ' '
to fix @MarkAmery's objection. (Thanks @YashaOlatoto.)
Here you go, just tweaked readsquare's answer to return an array of all classes:
function classList(elem){
var classList = elem.attr('class').split(/\s+/);
var classes = new Array(classList.length);
$.each( classList, function(index, item){
classes[index] = item;
});
return classes;
}
Pass a jQuery element to the function, so that a sample call will be:
var myClasses = classList($('#myElement'));
Might this can help you too. I have used this function to get classes of childern element..
function getClickClicked(){
var clickedElement=null;
var classes = null;<--- this is array
ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
clickedElement = $(e.target);
classes = clickedElement.attr("class").split(" ");
for(var i = 0; i<classes.length;i++){
console.log(classes[i]);
}
e.preventDefault();
});
}
In your case you want doler_ipsum class u can do like this now calsses[2];
.
$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})
Update:
As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).
const classes = element.className.split(' ').filter(Boolean);
or more modern
const classes = element.classList;
Old:
With all the given answers, you should never forget to user .trim() (or $.trim())
Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2 class3'..
This would turn into ['class1', 'class2','','','', 'class3']..
When you use trim, all multiple spaces get removed..