Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Toggle class by adding the class name when element is clicked and remove when clicked outside

  • Last Updated : 17 Dec, 2020

In this article, the task is to toggle a CSS class when clicked on that element and remove that particular class when clicked outside that element, that is, anywhere else in the HTML document.

Approach: This can be easily accomplished with the help of JavaScript by following the steps below:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

  • We will first select the element on which the class has to be toggled and the entire HTML document using the querySelector() method.
  • Next, we need to add the ‘click’ event listeners to both of the selected elements.
  • In the event listener of the element to be clicked, we will add the required CSS class using the classList.add() method.
  • In the event listener of the HTML document, we will first check if the clicked target is the above required element and then remove the class using the classList.remove() method, thereby toggling the class when clicked outside the above element.

Example: In this example, a button is defined in the HTML document on which the ‘active’ CSS class would be added once it is clicked. This ‘active’ class will also be removed from the button once we click anywhere elese in the HTML document.


<!DOCTYPE html>
        button {
            background-color: green;
            color: white;
            padding: 10px 24px;
            font-size: 18px;
            border: none;
            font-weight: bold;
            transition: all 0.4s;
            margin: 300px;
        .active {
            background-color: black;
        // Select the button on which the
        // class has to be toggled
        const btn = document.querySelector("button");
        // Select the entire HTML document
        const html = document.querySelector("html");
        // Add an event listener for 
        // a click to the button
        btn.addEventListener("click", function (e) {
            // Add the required class
        // Add an event listener for a
        // click to the html document
        html.addEventListener("click", function (e) {
            // If the element that is clicked on is
            // not the button itself, then remove
            // the class that was added earlier
            if ( !== btn)


My Personal Notes arrow_drop_up
Recommended Articles
Page :