Determining Element Class Presence in JavaScript
When inspecting an element's class attributes, it's often necessary to verify whether it contains a specific class. The provided code utilizes a switch statement to examine an element's exact class value, but this approach fails to detect partial matches.
To resolve this limitation, consider the use of the element.classList .contains method. This method accepts a class name as a parameter and returns a boolean indicating its presence within the element's class list:
element.classList.contains(class);
This method is universally supported across modern browsers and provides a consistent way to check for class inclusion.
Alternatively, for compatibility with older browsers that lack the .contains method, you can employ the following modified version of the indexOf method:
function hasClass(element, className) { return (' ' element.className ' ').indexOf(' ' className ' ') > -1; }
This modification ensures that you accurately detect partial matches, avoiding false positives when the class you seek is part of a larger class name.
Applying this method to the provided example:
var test = document.getElementById("test"), classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for(var i = 0, j = classes.length; iBy employing the .contains method or the modified indexOf function, you can reliably determine whether an element contains a specific class in JavaScript, regardless of browser compatibility or the presence of partial matches.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3