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

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

Susan Sarandon
Release: 2024-12-22 13:01:41
Original
495 people have browsed it

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

Is There a Method to Check if an HTML Element Contains a Specific Class in JavaScript?

Problem:

JavaScript beginners often rely on comparison of the className property to determine if an element contains a particular class. However, this approach fails when the element has multiple classes and the desired class is not the only one present.

Solution:

To address this issue, JavaScript provides the classList property and the contains method. The classList property returns a list of classes applied to the element, and the contains method checks if a specific class is included in that list.

const element = document.getElementById("test");
const hasClass1 = element.classList.contains("class1");
Copy after login

This approach works reliably regardless of the number of classes present on the element.

Alternative Approaches:

If classList is not supported in the target browser, an alternative method utilizing the indexOf function can be employed:

function hasClass(element, className) {
  return (" " + element.className + " ").indexOf(" " + className + " ") > -1;
}
Copy after login

Implementation:

To apply this approach to the example provided in the question, replace the original switch statement with the following code:

const element = document.getElementById("test");
const classes = ["class1", "class2", "class3", "class4"];

element.textContent = "";

for (let i = 0; i < classes.length; i++) {
  if (element.classList.contains(classes[i])) {
    element.textContent = `I have ${classes[i]}`;
    break;
  }
}
Copy after login

This code iterates through the expected classes and displays the first one that is present on the element.

The above is the detailed content of How to Reliably Check if an HTML 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