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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- How to build a Discord bot using TypeScript
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript