Javascript – Get class name using jQuery


I want to get the class name using jQuery

And if it has an id

<div class="myclass"></div>

Best Solution

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 // for IDs

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