Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class name using jQuery

I want to get the class name using jQuery

And if it has an id

<div class="myclass"></div> 
like image 687
X10nD Avatar asked Mar 08 '10 09:03

X10nD


People also ask

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.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

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


1 Answers

After getting the element as jQuery object via other means than its class, then

var className = $('#sidebar div:eq(14)').attr('class'); 

should do the trick. For the ID use .attr('id').

If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:

this.className // for classes, and this.id // for IDs 

Both are standard DOM methods and well supported in all browsers.

like image 54
Boldewyn Avatar answered Oct 31 '22 15:10

Boldewyn