Home > Web Front-end > JS Tutorial > How to Check for the Presence of a Class in an HTML Element Using JavaScript?

How to Check for the Presence of a Class in an HTML Element Using JavaScript?

Susan Sarandon
Release: 2024-11-19 17:57:03
Original
1041 people have browsed it

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);
Copy after login

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;
}
Copy after login

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template