Get class name using jQuery

Get class name using jQuery

I want to get the class name using jQuery
And if it has an id

Solutions/Answers:

Solution 1:

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.

Solution 2:

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

Solution 3:

Be Careful , Perhaps , you have a class and a subclass .

  <div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>

If you use previous solutions , you will have :

myclass mysubclass

So if you want to have the class selector, do the following :

var className = '.'+$('#id').attr('class').split(' ').join('.')

and you will have

.myclass.mysubclass

Now if you want to select all elements that have the same class such as div above :

   var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))

that means

var brothers=$('.myclass.mysubclass')

Update 2018

OR can be implemented with vanilla javascript in 2 lines:

  const { classList } = document.querySelector('#id');
  document.querySelectorAll(`.${Array.from(classList).join('.')}`);

Solution 4:

This is to get the second class into multiple classes using into a element

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];

Solution 5:

you can simply use,

var className = $('#id').attr('class');

Solution 6:

If your <div> has an id:

​<div id="test" class="my-custom-class"></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

…you can try:

var yourClass = $("#test").prop("class");

If your <div> has only a class, you can try:

var yourClass = $(".my-custom-class").prop("class");