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

How to Check for Class Existence in JavaScript Without jQuery?

Barbara Streisand
Release: 2024-11-19 18:32:03
Original
585 people have browsed it

How to Check for Class Existence in JavaScript Without jQuery?

Checking Class Existence with Plain JavaScript

In JavaScript, verifying whether an element contains a specific class can be achieved without relying on jQuery libraries.

One method involves using the className property:

var test = document.getElementById("test");
var testClass = test.className;

if (testClass.includes("class1")) {
  test.innerHTML = "I have class1";
} else {
  test.innerHTML = "";
}
Copy after login

However, this approach has limitations if multiple classes are present. For a comprehensive solution, utilize the classList.contains method:

element.classList.contains(class);
Copy after login

This method works across modern browsers with suitable polyfills for older versions.

Alternatively, the indexOf method can be used, but with an adjustment:

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

This ensures that partial matches within other class names are ignored.

To apply this to the provided example:

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

The above is the detailed content of How to Check for Class Existence in JavaScript Without jQuery?. 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