What is the use of the toggle() method in JavaScript?

The toggle() method in JavaScript is used to toggle the presence of a class on an element’s classList. If the class is present, it will be removed; if it is not present, it will be added. This allows you to easily toggle the visibility or behavior of an element on a web page.

For example:

// Select the element you want to toggle
const element = document.getElementById("myElement");

// Toggle a class on the element
element.classList.toggle("myClass");

In the above example, getElementById("myElement") is used to select an element with the id attribute of "myElement". The classList.toggle("myClass") method is then called on the selected element, with "myClass" being the name of the class you want to toggle.

You can also use the optional second parameter of the toggle() method to specify a boolean value that determines whether the class should be added or removed explicitly.

For example:

// Add a class to the element
element.classList.toggle("myClass", true);

// Remove a class from the element
element.classList.toggle("myClass", false);

This can be useful if you want to control the state of the class explicitly based on a condition. The toggle() method returns a boolean value indicating whether the class is currently present on the element after the toggle operation.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: