How to Toggle CSS Classes using the classList Property in JavaScript
Table of Contents
JavaScript makes it easy to control the user experience of the user.
One of the most useful things to do is being able to toggle classes on elements. This is useful for things like showing and hiding elements, or changing the appearance of an element.
In this post, we will look at how to toggle CSS classes using JavaScript.
How to toggle CSS classes
Let's say we have a button that we want to toggle the class of when it is clicked.
HTML<body>
<div class="enabled">Hello World</div>
<button class="toggle">Toggle</button>
</body>
The expectation is that when you click the button, the class of the div will be toggled from enabled
to disabled
and back again.
We can make use of the built-in classList
property of the element and use the toggle
method to toggle the class.
The classList
property is a read-only property that returns a live DOMTokenList
collection of the class attributes of the element. This collection contains the list of classes of the element. You can then use the toggle
method to toggle a class value; i.e., if the class exists, it is removed and if it doesn't, it is added.
JAVASCRIPTconst toggle = document.querySelector(".toggle");
const div = document.querySelector("div");
toggle.addEventListener("click", () => {
div.classList.toggle("enabled");
div.classList.toggle("disabled");
});
We can put this inside of a click listener on the button. When the button is clicked, we can run the code to toggle the class.
Then you can style each class however it makes sense:
CSS.enabled {
background-color: green;
}
.disabled {
background-color: red;
}
Keep in mind that you don't need to toggle between two different classes, you can also just toggle a single class:
JAVASCRIPTdiv.classList.toggle("enabled");
This will toggle the class of the div between enabled
and nothing.
Conclusion
In this post, we learned how to toggle CSS classes using JavaScript.
Simply use the classList
property of the element and use the toggle
method to toggle the class.
Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up a Local Web Server using Node.js