# JS Tip of the Day: Easily Toggle HTML Classes

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-easily-toggle-html-classes/643128>\
**Category:** web dev\
**Created:** [April 8, 2020, 12:19pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-easily-toggle-html-classes/643128 "2020-04-08T12:19:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [April 8, 2020, 12:19pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-easily-toggle-html-classes/643128/1 "2020-04-08T12:19:19Z")

</div>

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

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

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

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

```

More info:

- [classList on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
