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.
Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.
In my script, I want an
<a>
tag to turn help text on/off by giving the<a>
tag[some_class]
plus the class oftoggle
, and then giving it's help text the class of[some_class]_toggle
. This code is successfully finding the related elements using jQuery: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).
or more modern
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..
Here you go, just tweaked readsquare's answer to return an array of all classes:
Pass a jQuery element to the function, so that a sample call will be:
Try This. This will get you the names of all the classes from all the elements of document.
});
Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/