Search code examples
javascripthtmlcssdomhtmlelements

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


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...
}

Solution

  • 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...
    }