How to Use Toggle to Add a Class in JavaScript?

Estimated read time 1 min read

The classList.toggle() method in JavaScript can be used to add or remove a class from an element. If the class is not present, it will be added, and if it is present, it will be removed. Here’s an example:

let element = document.querySelector('#myElement');

In this example, the element with the ID myElement is selected using querySelector(). The classList.toggle() method is then used to toggle the presence of the class myClass on this element. If the class was not previously present, it will be added, and if it was already present, it will be removed.

You can also pass a second argument to classList.toggle() to specify whether the class should be added or removed, regardless of its current state. For example:

let element = document.querySelector('#myElement');
element.classList.toggle('myClass', true);

In this example, the second argument true specifies that the class myClass should be added to the element, even if it was already present. Conversely, you could pass false as the second argument to remove the class, even if it was not present.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply