Get class name using jQuery

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.


It is better to use .hasClass() when you want to check if an element has a particular class. This is because when an element has multiple class it is not trivial to check.

Example:

<div id='test' class='main divhover'></div>

Where:

$('#test').attr('class');        // returns `main divhover`.

With .hasClass() we can test if the div has the class divhover.

$('#test').hasClass('divhover'); // returns true
$('#test').hasClass('main');     // returns true