Check if an element contains a class in JavaScript?

daGUY picture daGUY · May 5, 2011 · Viewed 872.3k times · Source

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

Currently, I'm doing this:

The issue is that if I change the HTML to this...

<div id="test" class="class1 class5"></div>

...there's no longer an exact match, so I get the default output of nothing (""). But I still want the output to be I have class1 because the <div> still contains the .class1 class.

Answer

Felix Kling picture Felix Kling · May 5, 2011

Use element.classList .contains method:

element.classList.contains(class);

This works on all current browsers and there are polyfills to support older browsers too.


Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:

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

Otherwise you will also get true if the class you are looking for is part of another class name.

DEMO

jQuery uses a similar (if not the same) method.


Applied to the example:

As this does not work together with the switch statement, you could achieve the same effect with this code:

var test = document.getElementById("test"),
    classes = ['class1', 'class2', 'class3', 'class4'];

test.innerHTML = "";

for(var i = 0, j = classes.length; i < j; i++) {
    if(hasClass(test, classes[i])) {
        test.innerHTML = "I have " + classes[i];
        break;
    }
}

It's also less redundant ;)