How to Toggle CSS Classes using the classList Property in JavaScript

Updated onbyAlan Morel
How to Toggle CSS Classes using the classList Property in JavaScript

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.

<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.

const 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:

.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:

div.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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.