Home >Web Front-end >CSS Tutorial >How to Reliably Check if an HTML Element Contains a Specific Class in JavaScript?
Is There a Method to Check if an HTML Element Contains a Specific Class in JavaScript?
Problem:
JavaScript beginners often rely on comparison of the className property to determine if an element contains a particular class. However, this approach fails when the element has multiple classes and the desired class is not the only one present.
Solution:
To address this issue, JavaScript provides the classList property and the contains method. The classList property returns a list of classes applied to the element, and the contains method checks if a specific class is included in that list.
const element = document.getElementById("test"); const hasClass1 = element.classList.contains("class1");
This approach works reliably regardless of the number of classes present on the element.
Alternative Approaches:
If classList is not supported in the target browser, an alternative method utilizing the indexOf function can be employed:
function hasClass(element, className) { return (" " + element.className + " ").indexOf(" " + className + " ") > -1; }
Implementation:
To apply this approach to the example provided in the question, replace the original switch statement with the following code:
const element = document.getElementById("test"); const classes = ["class1", "class2", "class3", "class4"]; element.textContent = ""; for (let i = 0; i <p>This code iterates through the expected classes and displays the first one that is present on the element.</p>
The above is the detailed content of How to Reliably Check if an HTML Element Contains a Specific Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!