Open In App

How to Add an Active Class to the Current Element Using JavaScript?

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We can make use of JavaScript to add an active class to the current element by directly manipulating its class list. This involves identifying the element that triggered the interaction, removing the active class from any previously active elements, and then applying the active class to the current element.

We will explore two different approaches to add an active class to the current element with JavaScript:

Using Event Listeners

In this approach, we are using event listeners to manage the active class for interactive elements. When a button is clicked, the setActive() function is called, which removes the active class from all buttons and then adds it to the clicked button. This makes sure that only one button has the active class at a time, providing a clear visual indication of the currently selected button.

Example: The below example used Event Listeners to add an active class to the current element with JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Example 1</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h3>Approach 1: Using Event Listeners</h3>
    <div class="button" onclick="setActive(this)">Button 1</div>
    <div class="button" onclick="setActive(this)">Button 2</div>
    <div class="button" onclick="setActive(this)">Button 3</div>

    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 50px;
}

h1 {
    color: green;
}

h3 {
    color: #333;
}

.button {
    display: inline-block;
    padding: 10px 20px;
    margin: 10px;
    background-color: #ddd;
    border: 1px solid #ccc;
    cursor: pointer;
}

.active {
    background-color: #4CAF50;
    color: white;
}
JavaScript
function setActive(element) {
    const buttons = document
        .querySelectorAll('.button');
    buttons
        .forEach(button => button
            .classList.remove('active'));
    element
        .classList.add('active');
}

Output:

1
Output

Using a Common Parent with Event Delegation

In this approach, we are using a common parent with event delegation to manage the active class for list items. The click event is handled by the parent container (.topics-container), which listens for clicks on its child elements (.topic-item). When a child item is clicked, the event handler removes the active class from all items and then adds it to the clicked item, making sure that only one item is highlighted at a time.

Example: The below example uses Common Parent with Event Delegation to add an active class to the current element with JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
    			   initial-scale=1.0">
    <title>Example 2</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h3>Approach 2: Using a Common
        Parent with Event Delegation</h3>
    <div class="topics-container">
        <div class="topic-item">
            Data Structures</div>
        <div class="topic-item">
            Algorithms</div>
        <div class="topic-item">
            Programming Languages</div>
        <div class="topic-item">
            Web Development</div>
        <div class="topic-item">
            Interview Preparation</div>
    </div>

    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 50px;
}

h1 {
    color: green;
}

h3 {
    color: #333;
}

.topics-container {
    display: inline-block;
    text-align: left;
    margin-top: 20px;
}

.topic-item {
    padding: 10px;
    margin: 5px 0;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    cursor: pointer;
}

.active {
    background-color: #4CAF50;
    color: white;
}
JavaScript
document.querySelector('.topics-container')
    .addEventListener('click', function (event) {
        if (event.target
            .classList.contains('topic-item')) {
            document
                .querySelectorAll('.topic-item')
                .forEach(item => item.classList
                    .remove('active'));
            event
                .target.classList.add('active');
        }
    });

Output:

2
Output

Next Article

Similar Reads