How to check classlist with contains if a class exists before adding or removing it with JavaScript?

Estimated read time 1 min read

You can use the classList property of an element and the contains method to check if a class exists before adding or removing it.

Here’s an example of how you can check if a class exists before adding it to an element:

let element = document.querySelector("#myDiv");

if (!element.classList.contains("active")) {
  element.classList.add("active");
}

And here’s an example of how you can check if a class exists before removing it from an element:

let element = document.querySelector("#myDiv");

if (element.classList.contains("active")) {
  element.classList.remove("active");
}

In both examples, element is a reference to the DOM element you want to check or modify the class list of, and active is the class name that you’re checking for or adding/removing.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply