How can I JavaScript check if an element has class?
For example, if I have the following HTML:
<div id="test" class="class1 class5"></div>
I want to determine if this
contains the class class1. How can I do this without requiring an exact match?
How can I JavaScript check if an element has class?
For example, if I have the following HTML:
<div id="test" class="class1 class5"></div>
I want to determine if this
The simplest and most efficient way to check if an element has a specific class is to use the classList property with the contains() method. This method returns true if the class exists on the element.
var element = document.getElementById("test");
if (element.classList.contains("class1")) {
console.log("The element contains class1.");
}
You can also check if a class is present by examining the className property of the element. This method is less preferred because it requires handling spaces but works effectively.
var element = document.getElementById("test");
if (element.className.indexOf("class1") !== -1) {
console.log("The element contains class1.");
}
For a more flexible approach, especially if you want to ensure that the class name is matched as a whole word (not as a substring), you can use a regular expression.
var element = document.getElementById("test");
if (/\bclass1\b/.test(element.className)) {
console.log("The element contains class1.");
}