Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-11-13 00:57:02
Original
531 people have browsed it

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

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

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

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

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!

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