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
element.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:
<p id="elem" class="www ggg zzz"></p>
let elem = document.querySelector('#elem');
elem.classList.toggle('zzz');
The code execution result:
<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:
<p id="elem" class="www ggg"></p>
let elem = document.querySelector('#elem');
elem.classList.toggle('zzz');
The code execution result:
<p id="elem" class="www ggg zzz"></p>
See also
-
the
classList.add
method
that adds a given class -
the
classList.remove
method
that removes a given class -
the
classList.contains
method
that checks a given class