I want to get the class name using jQuery
And if it has an id
<div class="myclass"></div>
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.
$() = 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.
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".
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.
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