toggle class in javascript

How to Toggle Class in JavaScript

Introduction

Working with JavaScript can be very challenging but also very rewarding. One of the most common tasks you'll encounter is toggling classes. In this article, we'll talk about how to toggle class in JavaScript.

Using the classList.toggle() Method

The easiest way to toggle classes in JavaScript is by using the classList.toggle() method. This method adds a class to an element if it doesn't exist, or removes it if it does exist. Here's an example:

const button = document.querySelector('#button');
const box = document.querySelector('#box');

button.addEventListener('click', function() {
  box.classList.toggle('visible');
});

In this code, we select a button and a box element. When the button is clicked, we call the classList.toggle() method on the box element and pass in the 'visible' class name. If the box element doesn't have the 'visible' class, it will be added. If it does have the 'visible' class, it will be removed.

Using the Element.classList.add() and Element.classList.remove() Methods

If you don't want to use the classList.toggle() method, you can use the Element.classList.add() and Element.classList.remove() methods to add and remove classes manually. Here's an example:

const button = document.querySelector('#button');
const box = document.querySelector('#box');

button.addEventListener('click', function() {
  if (box.classList.contains('visible')) {
    box.classList.remove('visible');
  } else {
    box.classList.add('visible');
  }
});

In this code, we again select a button and a box element. When the button is clicked, we check if the box element has the 'visible' class using the Element.classList.contains() method. If it does, we remove the class using the Element.classList.remove() method. If it doesn't, we add the class using the Element.classList.add() method.

Conclusion

Now you know how to toggle class in JavaScript! Whether you use the classList.toggle() method or the Element.classList.add() and Element.classList.remove() methods, toggling classes is an essential skill for any JavaScript developer.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe