Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Add a Class to DOM Element in JavaScript?
Next article icon

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:

Table of Content

  • Using Event Listeners
  • Using a Common Parent with Event Delegation

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
How to Add a Class to DOM Element in JavaScript?

A

anjalibo6rb0
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to change style/class of an element using JavaScript ?
    In this article, we will learn how we can change the style/class of an element. If you want to build a cool website or app then UI plays an important role. We can change, add or remove any CSS property from an HTML element on the occurrence of any event with the help of JavaScript. There are two com
    4 min read
  • How to remove a Class name from an Element using JavaScript ?
    Removing a class name from an HTML element using JavaScript is often used to dynamically modify the styling or behavior of an element based on user interactions, events, or other conditions. The operation can be achieved using classList property, that allows you to add, remove, or toggle classes. Sy
    3 min read
  • How to Add a Class to DOM Element in JavaScript?
    Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.
    2 min read
  • How to append data to <div> element using JavaScript ?
    To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div.
    1 min read
  • How to add a class to the last paragraph element using jQuery ?
    In this article, we will learn to add a class to the last paragraph element using jQuery. To add a class to the last paragraph element, we use last() and addClass() methods. The jQuery last() function is an inbuilt function that is used to find the last element of the specified elements. Syntax: $(s
    1 min read
  • How to add/update an attribute to an HTML element using JavaScript?
    To add/update an attribute to an HTML element using JavaScript, we have multiple approaches. In this article, we are going to learn how to add/update an attribute to an HTML element using JavaScript. Below are the approaches used to add/update an attribute to an HTML element using JavaScript: Table
    2 min read
  • How to Filter a DIV Element Based on its Class Name using JavaScript?
    Div Element can be filtered based on class name for displaying specific content using JavaScript. Here, we will explore two different approaches to filtering a DIV element. Table of Content Using querySelectorAll and classListUsing getElementsByClassNameUsing querySelectorAll and classListIn this ap
    3 min read
  • How to Change the ID of Element using JavaScript?
    We are given an element and the task is to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. Syntax:Selected_element.id = newID;Below are the appraoche
    3 min read
  • How to Toggle an Element Class in JavaScript ?
    In JavaScript, toggling an element class refers to the process of dynamically adding or removing a CSS class from an HTML element. This allows developers to easily change an element's appearance or behavior in response to user actions, such as clicks or events. These are the following methods for to
    2 min read
  • JavaScript adding a class name to the element
    In JavaScript, adding a class name to an element allows you to style or manipulate it via CSS or JavaScript. This can be achieved using different methods. Here, we'll explore two common approaches: using the .className property and the .add() method. Below are the different approaches that could be
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences