How to Check if an Element Contains a Class in JavaScript
When working with elements in JavaScript, it's often useful to check if an element contains a specific class.
The Problem:
Using the traditional method of comparing the element's className property to the exact class name results in false positives when the element contains multiple classes. For instance, if the element has the class class1 and the code checks for class1, it will return false if the element also has other classes.
The Solution: element.classList.contains()
The modern solution is to use the element.classList.contains() method, which returns true if the element contains the specified class.
element.classList.contains(className);
This method works across all major browsers and has polyfills available for older browsers.
Alternative: indexOf() with Modification
For compatibility with older browsers, the indexOf() method can be used, but it requires a slight modification to avoid false positives:
function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }
Applied to the Example
Using the classList.contains() method, the provided code can be simplified to:
var test = document.getElementById("test"); var classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for (var i = 0, j = classes.length; i < j; i++) { if (test.classList.contains(classes[i])) { test.innerHTML = "I have " + classes[i]; break; } }
This approach eliminates redundancy and provides a more robust check for class presence.
The above is the detailed content of How to Check if an Element Contains a Specific Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!