Categories
JavaScript Answers

How to toggle an element’s class in pure JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *