Checking Class Existence with Plain JavaScript
In JavaScript, verifying whether an element contains a specific class can be achieved without relying on jQuery libraries.
One method involves using the className property:
var test = document.getElementById("test"); var testClass = test.className; if (testClass.includes("class1")) { test.innerHTML = "I have class1"; } else { test.innerHTML = ""; }
However, this approach has limitations if multiple classes are present. For a comprehensive solution, utilize the classList.contains method:
element.classList.contains(class);
This method works across modern browsers with suitable polyfills for older versions.
Alternatively, the indexOf method can be used, but with an adjustment:
function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }
This ensures that partial matches within other class names are ignored.
To apply this to the provided example:
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; } }
The above is the detailed content of How to Check for Class Existence in JavaScript Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!