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

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

It's the .className property, like this:

if (document.getElementById('element').className == "class_one") {
    //code...
}

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.


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

Tags:

Javascript

Dom