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.
To get the class names of a specific HTML Element as String, using JavaScript, get reference to this HTML element, and read the className property of this HTML Element. className property returns the classes in class attribute separated by space, in a String.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
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 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With