Get class name using jQuery

JavascriptHtmlJquery

Javascript Problem Overview


I want to get the class name using jQuery

And if it has an id

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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

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

Solution 5 - Javascript

you can simply use,

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

Solution 6 - Javascript

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");

Solution 7 - Javascript

If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:

" myclass1  myclass2 ".split(' ').join(".")

produces

".myclass1..myclass2."

I think you're better off using a regular expression to match on set of allowable characters for class names. For example:

" myclass1  myclass2  ".match(/[\d\w-_]+/g);

produces

["myclass1", "myclass2"]

The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.

Solution 8 - Javascript

To complete Whitestock answer (which is the best I found) I did :

className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');

So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'

Solution 9 - Javascript

<div id="elem" class="className"></div>

With Javascript

document.getElementById('elem').className;

With jQuery

$('#elem').attr('class');

OR

$('#elem').get(0).className;

Solution 10 - Javascript

You can get class Name by two ways :

var className = $('.myclass').attr('class');

OR

var className = $('.myclass').prop('class');

Solution 11 - Javascript

If you do not know the class name BUT you know the ID you can try this:

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

Then Call it using :

alert($('#currentST').attr('class'));

Solution 12 - Javascript

If you want to get classes of div and then want to check if any class exists then simple use.

if ( $('#div-id' ).hasClass( 'classname' ) ) {
    // do something...
}

e.g;

if ( $('body').hasClass( 'home' ) ) {
    $('#menu-item-4').addClass('active');
}

Solution 13 - Javascript

Try it

HTML

<div class="class_area-1">
    area 1
</div>

<div class="class_area-2">
    area 2
</div>

<div class="class_area-3">
    area 3
</div>

jQuery

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
    $('div').click(function(){
        alert($(this).attr('class'));
    });
</script>

Solution 14 - Javascript

This works too.

const $el = $(".myclass");
const className = $el[0].className;

Solution 15 - Javascript

if we have single or we want first div element we can use

$('div')[0].className otherwise we need an id of that element

Solution 16 - Javascript

Best way to get class name in javascript or jquery

attr() attribute function is used to get and set attribute.


> Get Class

jQuery('your selector').attr('class');  // Return class

> Check class exist or not

The hasClass() method checks if any of the selected elements have a specified class name.

 if(jQuery('selector').hasClass('abc-class')){
    	// Yes Exist
    }else{
    	// NOt exists
    }

> Set Class

jQuery('your selector').attr('class','myclass');  // It will add class to your selector

> Get Class on Click of button using jQuery

jQuery(document).on('click','button',function(){
	 var myclass = jQuery('#selector').attr('class');
});

> Add class if selector have no any class using jQuery

if ( $('#div-id' ).hasClass( 'classname' ) ) {
	    // Add your code
	}

> Get the second class into multiple classes using into a element

Change array position in place of [1] to get particular class.

var mysecondclass = $('#mydiv').attr('class').split(' ')[1];

Solution 17 - Javascript

If we have a code:

<div id="myDiv" class="myClass myClass2"></div> 

to take class name by using jQuery we could define and use a simple plugin method:

$.fn.class = function(){
  return Array.prototype.slice.call( $(this)[0].classList );
}

or

 $.fn.class = function(){
   return $(this).prop('class');
 } 

The use of the method will be:

$('#myDiv').class();

We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.

The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:

// [myClass, myClass2]
// "myClass myClass2"

Another important notice is that both methods as well as jQuery method

$('div').prop('class');

return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.

$('div:eq(2)').prop('class');

It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":

if($('#myDiv').hasClass('myClass')){
   // do something
}

as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:

$.fn.classes = function(){
   var o = $(this);
   return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
 } 

 var mySelector = $('#myDiv').classes();

The result will be:

// .myClass.myClass2

and you could get it to create dynamically a specific rewriting css rule for example.

Regards

Solution 18 - Javascript

Direct way

myid.className

console.log( myid.className )

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

Solution 19 - Javascript

use like this:-

$(".myclass").css("color","red");

if you've used this class more than once then use each operator

$(".myclass").each(function (index, value) {
//do you code
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionX10nDView Question on Stackoverflow
Solution 1 - JavascriptBoldewynView Answer on Stackoverflow
Solution 2 - JavascriptsandinoView Answer on Stackoverflow
Solution 3 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 4 - JavascriptSankarView Answer on Stackoverflow
Solution 5 - JavascriptMadura HarshanaView Answer on Stackoverflow
Solution 6 - Javascriptmg1075View Answer on Stackoverflow
Solution 7 - JavascriptWhitestockView Answer on Stackoverflow
Solution 8 - JavascriptPaul LeclercqView Answer on Stackoverflow
Solution 9 - JavascriptBilal IqbalView Answer on Stackoverflow
Solution 10 - JavascriptSadikhasanView Answer on Stackoverflow
Solution 11 - JavascriptLeroy GumedeView Answer on Stackoverflow
Solution 12 - JavascriptAamer ShahzadView Answer on Stackoverflow
Solution 13 - JavascriptJay ZalavadiyaView Answer on Stackoverflow
Solution 14 - JavascriptAdrian BartholomewView Answer on Stackoverflow
Solution 15 - Javascriptarunkumar tallaView Answer on Stackoverflow
Solution 16 - JavascriptMayank DudakiyaView Answer on Stackoverflow
Solution 17 - JavascriptChristiyanView Answer on Stackoverflow
Solution 18 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 19 - JavascriptSrujal PatelView Answer on Stackoverflow