24

How can I check in JavaScript if a DOM element contains a class?

I tried the following code, but for some reason it doesn't work...

if (document.getElementById('element').class == "class_one") {
    //code...
}
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Florian Müller
  • 7,448
  • 25
  • 78
  • 120
  • 1
    [`class` is reserved as a future keyword by the ECMAScript specification](https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words). Also, what if the element has more than 1 class? – Matt Ball Nov 23 '10 at 15:23

8 Answers8

50

To get the whole value of the class atribute, use .className

From MDC:

className gets and sets the value of the class attribute of the specified element.

Since 2013, you get an extra helping hand.

Many years ago, when this question was first answered, .className was the only real solution in pure JavaScript. Since 2013, all browsers support .classList interface.

JavaScript:

if(document.getElementById('element').classList.contains("class_one")) {
    //code...
}

You can also do fun things with classList, like .toggle(), .add() and .remove().

MDN documentation.

Backwards compatible code:

if(document.getElementById('element').className.split(" ").indexOf("class_one") >= 0) {
    //code...
}
Greg
  • 21,235
  • 17
  • 84
  • 107
16

The property you need is className, not class. Also, an element can have many classes, so if you want to test if it has a particular class you need to do something like the following:

function hasClass(el, clss) {
    return el.className && new RegExp("(^|\\s)" +
           clss + "(\\s|$)").test(el.className);
}

var element = document.getElementById('element');
if ( hasClass(element, "class_one") ) {
    // Do stuff here
}

UPDATE

Modern browsers (pretty much everything major except IE <= 9) support a classList property, as mentioned in @Dropped.on.Caprica's answer. It therefore makes sense to use this where available. Here's some example code that detects whether classList is supported by the browser and falls back to the regex-based code otherwise:

var hasClass = (typeof document.documentElement.classList == "undefined") ?
    function(el, clss) {
        return el.className && new RegExp("(^|\\s)" +
               clss + "(\\s|$)").test(el.className);
    } :
    function(el, clss) {
        return el.classList.contains(clss);
    };
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • +1, was about to post something like that. Just one thing, I guess you have to pass a class name (`"class_one"` is the one that the OP wants to check) in your `if (hasClass(...))` example. – Christian C. Salvadó Nov 23 '10 at 15:56
6

All modern browsers support the contains method of Element.classList :

testElement.classList.contains(className)

Demo

var testElement = document.getElementById('test');

document.body.innerHTML = '<pre>' + JSON.stringify({
    'main' : testElement.classList.contains('main'),
    'cont' : testElement.classList.contains('cont'),
    'content' : testElement.classList.contains('content'),
    'main-cont' : testElement.classList.contains('main-cont'),
    'main-content' : testElement.classList.contains('main-content')
}, null, 2) + '</pre>';
<div id="test" class="main main-content content"></div>

Supported browsers

enter image description here

(from CanIUse.com)


Polyfill

If you want to use Element.classList and you also want to support ancient browsers like IE8, consider using this polyfill by Eli Grey.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
5

It's the .className property, like this:

if (document.getElementById('element').className == "class_one") {
    //code...
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • @tereško - what is incorrect about this answer? Keep in mind the question being asked. – Nick Craver Jan 03 '13 at 13:49
  • 2
    it assumes that tag has only single class (and, in case if you want to update it - has nothing about [classList](https://developer.mozilla.org/en-US/docs/DOM/element.classList)). – tereško Jan 03 '13 at 13:52
  • 2
    @tereško - the question was "How can I check the class of a DOM element?", not "How do I check if a DOM element has a class?"...that question is elsewhere. – Nick Craver Jan 03 '13 at 13:53
  • @tereško - classList doesn't work until IE10, it's not really a feasible option for most. See here: http://caniuse.com/classlist – Nick Craver Jan 03 '13 at 13:54
  • I would be tempted to change `==` to `===` just for completeness (also less ambiguity). Otherwise this old answer still remains true. – rlemon Jan 03 '13 at 13:58
  • 1
    Well, `className` is *always* a string so it won't really make a difference. Unless you are jslint of course. ;) – ThiefMaster Jan 03 '13 at 14:01
  • @rlemon In what way is `==` ambiguous in this situation? – Tim Down Nov 20 '13 at 16:39
  • ambiguous may have been the wrong term. `==` forces me to think about coercion where there shouldn't be any. using strict equality is much more transparent for future you, or future developers looking at this statement. I wouldn't go so far as to say it is wrong, but I personally think in situations like this it shouldn't be used. – rlemon Nov 20 '13 at 18:34
3

A better solution than all of these (if you are using HTML5) is to use the classList API.

var element = document.getElementById('some-element');

if (element.classList.contains('class-you-want-to-check')) {
  console.log('element has target class')
} else {
  element.classList.add('class-you-want-to-check');
  element.classList.remove('class-you-want-to-check');
  element.classList.toggle('class-you-want-to-check');

  if (element.classList.contains('class-you-want-to-check')) {
    console.log('Yep, classList is baller')
  }
}
AlbertEngelB
  • 16,016
  • 15
  • 66
  • 93
0

toggleClass on element

var el = document.getElementById('element');
el.classList[['add','remove'][+el.classList.contains('class_one')]]('class_one');

or

el.classList.toggle('class_one');
zloctb
  • 10,592
  • 8
  • 70
  • 89
0

If you are using jQuery then just this simple code will help:

if ($('.yourclass').length) {
  // do something
} 

If you like to check more than 2 classes in the page then use $('.yourclass').length > 2

Syed
  • 15,657
  • 13
  • 120
  • 154
0

hasClass:

function hasClass(element, className) {
  return (element.className).indexOf(className) > -1;
}

containsClass:

function containsClass(element, className) {
  return Array.from(element.classList).filter(function (cls) {
    return cls.indexOf(className) > -1;
  }).length > 0;
}

codepen demo

oezkany
  • 201
  • 3
  • 10
  • Watch out on hasClass: If an element has class „show-initial“ and you test for class „show“ you‘ll get true even if the element does not have the class. – Florian Müller Jun 27 '19 at 18:45