Home >Web Front-end >CSS Tutorial >How to Reliably Check if a JavaScript Element Contains a Specific Class?

How to Reliably Check if a JavaScript Element Contains a Specific Class?

DDD
DDDOriginal
2024-12-24 18:42:59938browse

How to Reliably Check if a JavaScript Element Contains a Specific Class?

How to Check if an Element Contains a Class in JavaScript?

Problem:

Verifying if an element possesses a specific class is a common requirement in JavaScript. However, relying solely on className property comparisons, as demonstrated in the provided example, falters when the element holds multiple classes.

Solution:

To effectively ascertain the presence of a particular class, regardless of the total number of classes assigned to the element, utilize classList.contains method.

element.classList.contains(className);

This method functions flawlessly across modern browsers, and polyfills are available to cater to older browsers.

Alternative Approach:

For broader compatibility, consider employing indexOf with a slight modification:

function hasClass(element, className) {
    return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}

This adjustment ensures that partial class name matches do not yield erroneous results.

Demo:

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;
    }
}

In this example, the code efficiently identifies and displays the class present within the element, even if it's accompanied by other classes.

The above is the detailed content of How to Reliably Check if a JavaScript Element Contains a Specific Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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