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.
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.
jQuery does not really help you here...
javascript provides a classList attribute for a node element in dom. Simply using
will return a object of form
The object has functions like contains, add, remove which you can use
Why has no one simply listed.
On supporting browsers, you can use DOM elements'
classList
property.It is an array-like object listing all of the classes the element has.
If you need to support old browser versions that don't support the
classList
property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.The question is what Jquery is designed to do.
And why has no one given .find() as an answer?
There is also classList for non-IE browsers:
Here is a jQuery plugin which will return an array of all the classes the matched element(s) have
Use it like
In your case returns
You can also pass a function to the method to be called on each class
Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/
Minified Javascript