How to Toggle an Element’s Class using JavaScript?

Toggling a class is a very popular term in web development, especially when it comes to manipulating the appearance and behavior of HTML elements using CSS and JavaScript.

Toggling a class basically means adding or removing a CSS class from an HTML element dynamically using JavaScript.

This technique is often used to change the appearance of an element when a user interacts with it such as clicks, hovers, double clicks, etc.

In this technique, we actually add a CSS class to the element dynamically if it doesn’t have it and remove the class from the element if it does have it.

In this article, I’ll explain how you can toggle a CSS class with simple JavaScript code. So without any further ado, let’s begin.


Toggle a CSS Class using classList.toggle() Method

A straightforward way to toggle a CSS class in JavaScript is to use the classList.toggle() method.

The classList.toggle() method takes the class name as its argument and checks if the class exists on the given element or not.

element.classList.toggle(className);

If the given class already exists on the element, the toggle() method removes it from the element and if the given class doesn’t exist on the element, the toggle() method adds it to the element.

For example, let’s say we have a button and a div element in our HTML page. We also have a CSS class 'highlight' in our CSS file.

We want to toggle the 'highlight' class on and off the div element when the button is clicked:

<button id="toggleButton">Toggle highlight</button>
<div id="myDiv">This is some random text.</div>

Add the 'highlight' class to the CSS file:

.highlight{
   background-color: springgreen;
   padding: 20px;
   border-radius: 10px;
}

To detect if the button is clicked by the user or not, we can add an event listener to it using the addEventListener() method.

The addEventListener() method will call its callback function every time the button is pressed.

We can put all our logic to toggle the class inside the callback function so that it gets executed on each button click:

// Get references to the elements
const toggleButton = document.getElementById("toggleButton");
const element = document.getElementById("myDiv");

// Fires on button click
toggleButton.addEventListener("click", function() {
    
    // Toggle the highlight class
    element.classList.toggle("highlight");
  
});

Output:

Toggle a CSS class with JavaScript

As you can see from the above output, initially, the ‘highlight’ class isn’t present on the div, therefore, when the button is clicked it is added to the element.

But if you again click the button, the ‘highlight’ class is removed from the div.


Toggle class by Manually Adding and Removing from the Element

In the last example, we used the built-in classList.toggle() method to toggle the CSS class.

But if you don’t want to use the toggle() method, you can also manually add and remove the CSS class from the element.

To manually toggle a class on and off an element, we need the following three methods:

  • classList.contains(className) – Returns true if the given class exists on the element. Otherwise returns false.
  • classList.add(className) – Adds given class to the element.
  • classList.remove(className) – Removes the given class from the element.

We’ll use the contains() method to check if the class already exists on the element or not.

If the contains() method returns true, it means the class is already there. Therefore, we’ll have to remove it from the element using the classList.remove() method.

If the contains() method returns false, it means the class doesn’t present on the element. Therefore, we’ll have to add the class to the element using classList.add() method.

<button id="toggleButton">Toggle Class</button>
<div id="myDiv">This is some random text.</div>

Add the CSS:

.highlight{
   background-color: springgreen;
   padding: 20px;
   border-radius: 10px;
}

Add the JavaScript:

// Get references to the elements
const toggleButton = document.getElementById("toggleButton");
const element = document.getElementById("myDiv");

// Fires on button click
toggleButton.addEventListener("click", function() {
    
    // Checks if class already exists
    if(element.classList.contains('highlight')){
        // Remove the class
        element.classList.remove('highlight');
    }
    else{
        // Add the class
        element.classList.add('highlight');
    }

});

Output:

Toggle class manually with JavaScript

Toggle Between Two Classes with JavaScript

The classList.toggle() method has a limitation that it can only toggle a single class at a time.

So, if you want to toggle between two CSS classes, you have to manually add and remove them.

For example, if one class exists on the element, you have to manually remove it and then add the other class.

Let’s take the same example again and try to toggle between two classes 'yellow' and 'green':

<button id="toggleButton">Toggle Classes</button>
<div id="myDiv" class="yellow">This is some random text.</div>

Add the two classes to your stylesheet:

.yellow{
    background-color: yellow;
    padding: 20px;
    border-radius: 10px;
}
.green{
    background-color: springgreen;
    padding: 20px;
    border-radius: 10px;
}

Add the JavaScript code:

// Get references to the elements
const toggleButton = document.getElementById("toggleButton");
const element = document.getElementById("myDiv");

// Fires on button click
toggleButton.addEventListener("click", function() {
    
    // Checks if 'yellow' class already exists
    if(element.classList.contains('yellow')){
        element.classList.remove('yellow');
        element.classList.add('green');
    }
    else{
        element.classList.add('yellow');
        element.classList.remove('green');
    }

});

Output:

Toggle between two classes with JavaScript

Conclusion

In this article, we learned why we need to toggle a CSS class and how we can do it with the help of JavaScript.

In summary, an straightforward way to toggle an element’s class is to use the built-in classList.toggle() method.

The toggle() method takes the class name as a parameter and toggles it.

You can also manually toggle a class by using the contains(), add() and remove() methods of the classList object.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.