views:

7246

answers:

3

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.

<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

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.

+26  A: 

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

Then you can iterate all of them and find the one you want.

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

Note jQuery does not really help you here but here is a jQuery version

var classList =$('#divId').attr('class').split(/\s+/);
$.each( classList, function(index, item){
    if (item==='someClass') {
       //do something
    }
});
redsquare
that is exactly what i woud have done, but i was not sure if there was a build in jQuery function that gave you a collection of the classes.
Sander
There is not no
redsquare
This is what I was looking for. Thanks!
Buggabill
FYI: jQuery uses className.split(/\s+/)
David Kemp
A: 

I know this is an outdated post however you can do this to remove all classes:

$("#divId").attr('class','');
jason
+4  A: 

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);
gesellix