Home >Web Front-end >JS Tutorial >How to Efficiently Check for Element Class Presence in JavaScript?
Checking for Element Class Presence in JavaScript
Using basic JavaScript, how can you determine whether an element contains a specific class? When using the className property, an exact class match is required, leading to limitations when an element has multiple classes.
Solution: element.classList.contains
Element.classList exposes a .contains method specifically designed for this purpose:
element.classList.contains(className);
This method is supported by all modern browsers and can be polyfilled for older versions.
Alternative: Using indexOf
Alternatively, you can utilize element.className and indexOf for older browsers that lack classList support, but minor adjustments are necessary to ensure accuracy:
function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1; }
This ensures that the sought class is not a substring of another class name.
Code Example
To apply this solution to your specific situation:
var test = document.getElementById("test"); var classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for(var i = 0, j = classes.length; i <p>This code employs a more efficient approach by looping through a predefined array of potential classes, reducing redundancy and improving maintainability.</p>
The above is the detailed content of How to Efficiently Check for Element Class Presence in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!