Toggle a Class of an Element

To toggle a class of an element, you use the toggle() method of the classList property of the element:

element.classList.toggle(className);Code language: CSS (css)

If the element has the className, the toggle() method removes it. If the element doesn’t have the className, the toggle() method adds the className to the classList.

Suppose you have the following element:

<div class="show">Item</div>Code language: HTML, XML (xml)

The following illustrates how to toggle the show class of the <div> element:

const div = document.querySelector('div');
div.classList.toggle('show');Code language: JavaScript (javascript)
Was this tutorial helpful ?