toggle method of the classList object

The toggle method of the classList object toggles a given CSS class of an element: adds the class if it doesn't exist and removes it if it does.

Syntax

javascriptelement.classList.toggle(class);

Example

In this example, when using the toggle method, the class zzz will be removed, since it is already in the element:

html<p id="elem" class="www ggg zzz"></p>
javascriptlet elem = document.querySelector('#elem');
elem.classList.toggle('zzz');

The code execution result:

html<p id="elem" class="www ggg"></p>

Example

In this example, when using the toggle method, the class zzz will be added, since it is not present in the element:

html<p id="elem" class="www ggg"></p>
javascriptlet elem = document.querySelector('#elem');
elem.classList.toggle('zzz');

The code execution result:

html<p id="elem" class="www ggg zzz"></p>

See also