659

I want to get the class name using jQuery

And if it has an id

<div class="myclass"></div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • 2
    @Amarghosh: True, true, but you could actually get into this situation, if you use some traversal methods like `parents()`. – Boldewyn Mar 08 '10 at 09:49
  • 8
    fyi `this.className` works without jquery (would return `"myclass"` in above example) – Peter Berg Apr 07 '13 at 06:01

19 Answers19

1150

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.

Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • 7
    and if its an ID var IDName = $('#id').attr('id'); – X10nD Mar 08 '10 at 09:48
  • 19
    As sandino points out in his answer, there is always a chance of more than one class name being set. (for instance JQuery-UI adds helper classes all over the place). You could always checked for this using `if(className.indexOf(' ') !== -1){throw new Error('Uh-oh! More than one class name!');}` – Potherca Jun 11 '11 at 20:43
  • 18
    If you leverage `.attr('class')` and combine it with `if(className.indexOf('Class_I_am_Looking_For') > = 0)` you can easily check for the existence a specific class and still handle multiple classes. – RonnBlack Oct 28 '12 at 09:35
  • 20
    RonnBlack: `if(className.indexOf('Class_I_am_Looking_For') > = 0)` will also match `"This_Is_Not_the_Class_I_am_Looking_For"` – Leif Neland Jun 05 '13 at 10:46
  • you have to split on whitespace so: function isClassInString(className, classToCheck) { var classes = className.split("\\s+"); for (var j=0; j – SRM Jun 16 '13 at 21:41
  • It’s time to come back here. The white-space splitting of `@class` was never an issue. This was, especially, not the original question. All the OP asked was, how to get the “class name”, which translates to “content of the `class` attribute” (as proven by accepting the answer). @sandino’s answer is good, but perhaps the use case of the OP was to copy classes from one element to another? In this case `.hasClass()` is virtually useless. Who knows? – Boldewyn Jun 17 '13 at 07:26
  • What about with the this keyword? http://stackoverflow.com/questions/22665134/getting-an-id-from-jquerys-this – Ben Racicot Mar 26 '14 at 15:09
  • 1
    @BenRacicot in that case, simply use [standard DOM methods](https://developer.mozilla.org/en-US/docs/Web/API/Element.className). – Boldewyn Mar 26 '14 at 15:23
  • @Boldewyn I may be missing something here. If you already know the class name (e.g. myclass) what is the point of using this code?`$('.myclass').attr('class');` – nam Feb 15 '17 at 21:08
  • You may be knowing _one_ of several class names. Or you do have another reference to that element, like `$(document.getElementById('foo'))`. This question and answer target specifically at how to learn _all_ classes, that a given element possesses. I agree, that the example is not chosen too luckily, though. – Boldewyn Feb 16 '17 at 07:21
249

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
Argyle
  • 3,324
  • 25
  • 44
sandino
  • 3,813
  • 1
  • 19
  • 24
  • 13
    But what if you *don't* know the classname? ;-) – Potherca Jun 11 '11 at 20:41
  • 10
    that's right...this is only usefull if you know the classname you are checking...but my comment was to alert you not to use .attr('class')=='CLASSNAME_YOU_ARE_SEARCHING' to check if a dom element has some class instead it's better to use .hasClass – sandino Jun 15 '11 at 19:45
  • 5
    Another way is to use `.is('.divhover')` – orad Dec 12 '12 at 20:09
  • Is it possible to loop over classes of an element? – Fractaliste Mar 03 '15 at 15:07
  • 3
    Yes it is just do $(element).attr("class").split(' '); and you get a list then just use a for or foreach loop – sandino Apr 15 '15 at 22:15
47

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('.')}`);
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 6
    There may be more than one space between classes. More correct variant var className = '.'+$('#id').attr('class').replace(/ +(?= )/g,'').split(' ').join('.') – Suhan Nov 26 '13 at 10:59
  • 3
    An even more correct expression is `'.'+$('#id').attr('class').split(/[ \n\r\t\f]+/).join('.')`, because [space, Tab, LF, CR and FF](http://www.w3.org/html/wg/drafts/html/CR/infrastructure.html#space-character) are allowed to separate classes. (`.split()` also accepts RegExps.) – Boldewyn Jul 07 '14 at 07:28
  • `'.'+$('#id').attr('class').split(/\s+/).join('.')` would be more concise, wouldn't it? Or would that match something I'm not thinking about? – LostHisMind Jan 30 '15 at 23:59
  • 1
    To be safe and not get any trailing dot, with any of these solutions, add a trim like this `.attr('class').trim().split(...)` – Christian Lavallee Mar 16 '16 at 21:08
31

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

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];
Sankar
  • 652
  • 6
  • 13
17

you can simply use,

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

Madura Harshana
  • 1,299
  • 8
  • 25
  • 40
12

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");
mg1075
  • 17,985
  • 8
  • 59
  • 100
7

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.

Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
Whitestock
  • 81
  • 1
  • 1
6

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'

Paul Leclercq
  • 989
  • 2
  • 15
  • 26
6
<div id="elem" class="className"></div>

With Javascript

document.getElementById('elem').className;

With jQuery

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

OR

$('#elem').get(0).className;
Bilal Iqbal
  • 315
  • 3
  • 9
5

You can get class Name by two ways :

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

OR

var className = $('.myclass').prop('class');
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
3

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

Christiyan
  • 485
  • 5
  • 5
2

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'));
LeRoy
  • 4,189
  • 2
  • 35
  • 46
2

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');
}
Aamer Shahzad
  • 2,617
  • 1
  • 27
  • 25
2

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

This works too.

const $el = $(".myclass");
const className = $el[0].className;
Adrian Bartholomew
  • 2,506
  • 6
  • 29
  • 37
0

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

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

0

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];
Mayank Dudakiya
  • 3,635
  • 35
  • 35
0

Direct way

myid.className

console.log( myid.className )
<div id="myid" class="myclass"></div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
-3

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
}
Srujal Patel
  • 145
  • 8