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...
}
To get the whole value of the class atribute, use .className
className gets and sets the value of the class attribute of the specified element.
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()
.
Backwards compatible code:
if(document.getElementById('element').className.split(" ").indexOf("class_one") >= 0) {
//code...
}