Sometimes, we want to toggle an element’s class in pure JavaScript.
In this article, we’ll look at how to toggle an element’s class in pure JavaScript.
How to toggle an element’s class in pure JavaScript?
To toggle an element’s class in pure JavaScript, we can use the classList.toggle
method.
For instance, we write
const menu = document.querySelector(".menu");
menu.classList.toggle("hidden-phone");
to select the element with class menu
with querySelector
.
And then we call menu.classList.toggle
to toggle the hidden-phone
class on the menu
element.
Conclusion
To toggle an element’s class in pure JavaScript, we can use the classList.toggle
method.