Friday, 21 July 2017

javascript - Get class list for element with jQuery



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.



Hello World!



I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.



Answer



You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.



Then you can iterate and find the one you want.



var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}

}


jQuery does not really help you here...



var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item === 'someClass') {
//do something
}

});

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...