JS Tip of the Day: Easily Toggle HTML Classes

Easily Toggle HTML Classes
Level: Beginner

Sometimes you may want to toggle a class of an HTML element on and off depending on whether or not it already exists. You can do this using the toggle() method of an element’s classList object.

The following example toggles the “active” class on a button every time its clicked changing the button’s background depending on whether or not the class is applied.

<style>
button {
  background-color: lemonchiffon;
}
.active {
  background-color: lavender;
}
</style>

<button id="toggle">Toggle Me</button>

<script>
let button = document.getElementById('toggle');
button.addEventListener('click', event => {
    button.classList.toggle('active');
});
</script>

The default behavior of toggle() is removing a class if its there or adding it if its not. Using its second argument, you can also force a class to be added or removed.

classList.toggle('active', true); // same as classList.add('active')
classList.toggle('active', false); // same as classList.remove('active')

This way toggle() can act as an easy way to go between adding or removing a class based on a condition or the value of a variable. The following changes for the code in the earlier example makes it so the class is only added to the button if the SHIFT key is pressed when it is clicked.

let button = document.getElementById('toggle');
button.addEventListener('click', event => {
    button.classList.toggle('active', event.shiftKey);
});

More info: