The toggle() method of the classList property can be used to toggle a CSS class from an HTML element. This method takes in the class name as input, and toggle it.

If the class already exists in the element's classList, it is removed. Otherwise, it adds it to the classList.

Let us say you have got the following HTML element:

<div class="pizza">🍕</div>

The following example demonstrates how you can add more olive to the pizza by using the toggle() method:

const div = document.querySelector('div');


The classList property works in all modern browsers, and IE10 and above.

Take a look at this article to learn more about adding, removing, and toggling CSS classes in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.