Adding event listeners to elements with a specific class is a common task in web development, allowing you to respond to user interactions with elements that share a common identifier. In this guide, we’ll explore different methods to achieve this using JavaScript.
Setting the stage: Sample HTML and JS Code
Let’s start with a simple example to set the context. Consider the following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Listener Demo</title>
<style>
.clickable {
cursor: pointer;
color: blue;
}
</style>
</head>
<body>
<p class="clickable">Element 1</p>
<p class="clickable">Element 2</p>
<p class="clickable">Element 3</p>
<script src="script.js"></script>
</body>
</html>
Now, let’s add an event listener to all elements with the class “clickable” using JavaScript.
Method 1: Using document.querySelectorAll(), forEach(), and addEventListener()
- We use document.querySelectorAll(‘.clickable’) to select all elements with the class “clickable.”
- The forEach method iterates over each selected element.
- We attach an event listener using addEventListener(‘click’, …) to respond to click events.
// script.js
const clickableElements = document.querySelectorAll('.clickable');
clickableElements.forEach(element => {
element.addEventListener('click', () => {
console.log('Element clicked:', element.textContent);
// Your custom logic goes here
});
});
Method 2: Using document.getElementsByClassName
Alternatively, can use below approach.
// script.js
const clickableElements = document.getElementsByClassName('clickable');
for (const element of clickableElements) {
element.addEventListener('click', () => {
console.log('Element clicked:', element.textContent);
// Your custom logic goes here
});
}
Both approaches achieve the same result, and you can choose the one that fits your needs.
Choosing the Event Type
Customize the type of event you want to listen for by replacing ‘click’ with the desired event type. For a list of available event types, refer to the MDN event list here.
Method 3: Using a for…of Loop
If you prefer traditional loops, you can use a for…of
loop as an alternative to forEach()
:
// script.js
const clickableElements = document.querySelectorAll('.clickable');
for (const element of clickableElements) {
element.addEventListener('click', () => {
console.log('Element clicked:', element.textContent);
// Your custom logic goes here
});
}
🧪Practice Coding Problem: Magic Button Click
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Create a button with the class “magic-btn” and add an event listener to log “Abracadabra!” to the console when the button is clicked. You can write code in
script.js
.JavaScript<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Magical Button</title> <style> .magic-btn { padding: 10px; background-color: purple; color: white; cursor: pointer; } </style> </head> <body> <button class="magic-btn">Cast Spell</button> <script src="script.js"></script> </body> </html>
Please attempt before seeing the Answer:
// script.js
const magicButton = document.querySelector('.magic-btn');
magicButton.addEventListener('click', () => {
console.log('Abracadabra!');
// Can do more Magical Shenanigans here! 🔮
});
Hope you will make all those HTML elements listen to your Javascript. Keep coding and casting those programming spells! ✨🧙♂️💻