Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Check if an element contains a class in JavaScript?

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

Currently, I'm doing this:
var test = document.getElementById("test");
var testClass = test.className;

switch (testClass) {
case "class1":
test.innerHTML = "I have class1";
break;
case "class2":
test.innerHTML = "I have class2";
break;
case "class3":
test.innerHTML = "I have class3";
break;
case "class4":
test.innerHTML = "I have class4";
break;
default:
test.innerHTML = "";
}

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


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

3 Answers

aashaykumar
Use element.classList .contains method:

element.classList.contains(class);

This works on all current browsers and there are polyfills to support older browsers too.
kshitijrana14
The easy and effective solution is trying .contains method.
test.classList.contains(testClass);
sandhya6gczb
In modern browsers, you can just use the contains a method of Element.classList :

testElement.classList.contains(className)

Login / Signup to Answer the Question.