Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

<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.

like image 968
Buggabill Avatar asked Aug 04 '09 12:08

Buggabill


People also ask

How do I get all the classes of elements?

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

How do I get the class of an element in HTML?

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.

How do you check class is exists in jQuery?

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".

How do I select a class in jQuery?

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.


1 Answers

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     } }); 
like image 66
redsquare Avatar answered Oct 13 '22 08:10

redsquare