How to Add a Class to a Clicked Element in JavaScript
A common feature in interactive web design is to visually change an element when a user clicks on it. This could be highlighting a selected item in a list, marking a navigation link as "active," or triggering a style change. The standard and most effective way to do this is by adding a CSS class to the specific element that was clicked.
This guide will teach you the two primary methods for accomplishing this. You will learn the powerful and efficient event delegation technique, which uses a single event listener to manage clicks on multiple elements. You will also learn the more direct approach of adding an event listener to each individual element.
The Goal: Identifying the Clicked Element
When an event (like a click) occurs, the browser creates an event object. This object contains a wealth of information about the interaction, but the most important property for our task is event.target.
event.target: This property is a direct reference to the specific DOM element that was clicked.
Once we have event.target, we can use its classList.add() method to add a class.
Method 1 (Recommended): Using Event Delegation
Event delegation is the most efficient and scalable technique. Instead of adding a separate event listener to every single element, you add one single listener to a common parent element. When a click occurs, the listener uses event.target to identify which child element was actually clicked.
The logic:
- Add a
clickevent listener to a parent container (or even thedocumentitself). - Inside the listener's callback function,
event.targetwill be the element that the user clicked. - Add the desired class to
event.target.
The HTML:
<div id="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
The solution:
// Get the parent container
const container = document.getElementById('container');
container.addEventListener('click', (event) => {
// Check if the clicked element is one of the boxes
if (event.target.classList.contains('box')) {
// event.target is the specific div that was clicked
event.target.classList.add('bg-yellow');
}
});
This is the best practice because it is very performant and works even if new .box elements are added to the container later.
Method 2: Adding an Event Listener to Each Element
For a small, fixed number of elements, you can add an event listener to each one individually.
The logic:
- Select all the target elements using
querySelectorAll(). - Loop through the resulting
NodeList. - In each iteration, add a
clickevent listener directly to that element.
The solution:
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => {
box.addEventListener('click', () => {
// Here, 'box' refers to the element in the current iteration
box.classList.add('bg-yellow');
});
});
This method is simpler to understand for beginners but is less performant if you have a very large number of elements.
How to Add Multiple Classes at Once
The classList.add() method can accept multiple class names as separate arguments.
document.addEventListener('click', (event) => {
// Add three different classes to the clicked element
event.target.classList.add('bg-yellow', 'text-bold', 'selected');
});
How to Toggle a Class on Click
A more common use case is to toggle a class—add it on the first click, remove it on the second, and so on. The classList.toggle() method is perfect for this.
const container = document.getElementById('container');
container.addEventListener('click', (event) => {
if (event.target.classList.contains('box')) {
// If 'bg-yellow' exists, it's removed. If not, it's added.
event.target.classList.toggle('bg-yellow');
}
});
Practical Example: A "Selectable List"
This script allows a user to click on items in a list. The clicked item gets an "active" class. To ensure only one item is active at a time, we first remove the class from all other items.
The HTML code:
<ul id="menu">
<li class="menu-item">Home</li>
<li class="menu-item">About</li>
<li class="menu-item">Contact</li>
</ul>
The JavaScript code:
const menu = document.getElementById('menu');
const menuItems = menu.querySelectorAll('.menu-item');
menu.addEventListener('click', (event) => {
const clickedItem = event.target;
// Only proceed if a menu-item was clicked
if (clickedItem.classList.contains('menu-item')) {
// First, remove the 'active' class from all items
menuItems.forEach(item => {
item.classList.remove('active');
});
// Then, add the 'active' class to only the clicked item
clickedItem.classList.add('active');
}
});
Conclusion
Adding a class to a clicked element is a fundamental technique for creating interactive user interfaces.
- The
event.targetproperty is the key to identifying which element was clicked. - Event delegation (adding one listener to a parent) is the most efficient and recommended method for handling clicks on multiple elements.
- Use
element.classList.add()to add a class, or the more versatileelement.classList.toggle()for on/off behaviors.