Home >Web Front-end >JS Tutorial >How to Check for the Presence of a Class in an HTML Element Using JavaScript?
Checking Element Class Presence with JavaScript
In JavaScript, determining if an HTML element possesses a particular class can be easily achieved using modern browsers' inherent classList object. The method classList .contains() allows you to verify the presence of a class on an element. Its syntax is as follows:
element.classList.contains(class);
This approach is supported by all current browsers, and polyfills are available for older browsers.
Alternative Approach for Legacy Browsers
If compatibility with older browsers is crucial and you prefer to avoid polyfills, an alternative method utilizing indexOf() is available:
function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1; }
This optimized approach ensures that only exact class matches are detected, preventing false positives from partial class matches.
Applying the Solutions to the Provided Example
In the example provided, the switch statement cannot be used with the classList and indexOf methods. However, you can achieve the same result with the following code:
var test = document.getElementById("test"), classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for(var i = 0, j = classes.length; i < j; i++) { if(hasClass(test, classes[i])) { test.innerHTML = "I have " + classes[i]; break; } }
This revised code is more concise and eliminates redundant checks while accurately identifying the class presence in the HTML element.
The above is the detailed content of How to Check for the Presence of a Class in an HTML Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!