How to add an active class to the current element with JavaScript?

Adding an active class to the current element allows you to highlight the selected item in navigation menus, tabs, or button groups. This technique uses JavaScript event listeners to dynamically manage CSS classes.

Complete Example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   .btn {
      border: none;
      outline: none;
      padding: 10px 16px;
      background-color: #6ea2f0;
      cursor: pointer;
      color: white;
      font-size: 18px;
      margin: 5px;
   }
   .active, .btn:hover {
      background-color: #666;
      color: white;
   }
</style>
</head>
<body>
<h1>Active Button Example</h1>
<div id="sampleDiv">
<button class="btn">Giraffe</button>
<button class="btn active">Cow</button>
<button class="btn">Lion</button>
<button class="btn">Leopard</button>
<button class="btn">Cheetah</button>
</div>
<h2>Click any button to make it active</h2>

<script>
   var btns = document.querySelectorAll(".btn");
   Array.from(btns).forEach(item => {
      item.addEventListener("click", () => {
         // Remove active class from all buttons
         var selected = document.getElementsByClassName("active");
         if (selected.length > 0) {
            selected[0].className = selected[0].className.replace(" active", "");
         }
         // Add active class to clicked button
         item.className += " active";
      });
   });
</script>
</body>
</html>

How It Works

The JavaScript code follows these steps:

  1. Select all buttons: querySelectorAll(".btn") gets all elements with the "btn" class
  2. Add event listeners: Each button gets a click event listener
  3. Remove existing active class: Find the currently active element and remove its "active" class
  4. Add active class: Add "active" class to the clicked element

Alternative Method Using classList

A more modern approach uses the classList API for cleaner code:

<script>
   const buttons = document.querySelectorAll('.btn');
   
   buttons.forEach(button => {
      button.addEventListener('click', () => {
         // Remove active from all buttons
         buttons.forEach(btn => btn.classList.remove('active'));
         
         // Add active to clicked button
         button.classList.add('active');
      });
   });
</script>

Key Points

  • CSS Styling: The .active class defines the visual appearance of the selected state
  • Event Delegation: Each button has its own click listener for direct handling
  • Class Management: Remove active from all elements before adding to the current one
  • Error Prevention: Check if an active element exists before removing the class

Common Use Cases

  • Navigation menus with active page indicators
  • Tab interfaces with selected tab highlighting
  • Filter buttons in galleries or lists
  • Toggle buttons in toolbars

Conclusion

Adding active classes to current elements enhances user experience by providing visual feedback. Use classList.add() and classList.remove() for cleaner, more maintainable code when managing CSS classes dynamically.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements