How to toggle class using pure JavaScript in HTML?

Sometimes, we want to toggle class using pure JavaScript in HTML.

In this article, we’ll look at how to toggle class using pure JavaScript in HTML.

How to toggle class using pure JavaScript in HTML?

To toggle class using pure JavaScript in HTML, we use the classList property.

For instance, we write

const container = document.querySelector("#container");

container.addEventListener("mouseenter", (e) => {
  e.target.classList.remove("first");
  e.target.classList.add("second");
});

container.addEventListener("mouseleave", (e) => {
  e.target.classList.add("first");
  e.target.classList.remove("second");
});

to select the element with querySelector.

Then we call addEventListener to listen to the mouseenter and `mouseleave events.

In the listeners, we call e.target.classList.remove to remove the class from the current element.

And we use e.target.classList.add to add a class to the current element.

Conclusion

To toggle class using pure JavaScript in HTML, we use the classList property.