How to Add Active Class in Javascript

In this tutorial, you will learn how to add active class in javascript.  Generally, active class is used in navigation links.  Whenever a user clicks on a particular navigation link, we add an active class to it.

Active class is not limited to links.  You can add it to any element of your choice. You can specify your styles and add them to an element when you think it is considered to be active.

Each element has classList property and this property points to an object that has 2 methods add() and remove().  The add() method is used to add a class to the element and the remove() method is used to remove a class from the element.

In the following example, we have 5 buttons and when we click any of the buttons, we will simply add an active class to it.  As a result, the background of the button will be changed to green color. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 2 elements in the HTML file (div and button). The div element with a class of container is just a wrapper for the rest of the elements.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div class="container">
        <button>1</button>
        <button>2</button>
        <button>3</button>
        <button>4</button>
        <button>5</button>
    </div>
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

.container {
    display: inline-block;
}

button {
    border: none;
    background-color: grey;
    font-size: 20px;
    color: #fff;
    padding: 10px 20px;
    cursor: pointer;
}

.active, button:hover {
    background-color: green;
}

Javascript

  • We have selected all button elements using the document.querySelectorAll() method and stored them in buttons variable.
  • We are using the forEach() method to loop through all the button elements.
  • We are adding a click event listener to each button element.
  • In the event handler function, we are using the forEach() method to loop through all button elements and removing the active class if there is any, using the remove() method.
  • We are using this keyword to get the currently clicked button element and adding an active class to it using add() method.
let buttons = document.querySelectorAll('button');

buttons.forEach(button => {
    button.addEventListener('click', function () {
        buttons.forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');        
    });
});