How to Add Event Listeners to Multiple Elements using JavaScript
Events are an important part of the modern web. The browser fires off events like clicks, key presses, and mouse movements, and we can listen for these events to then execute code.
Adding a single event listener is easy, but adding multiple event listeners can be a little more involved.
In this post, we're going to look at the best way to add multiple event listeners.
Adding Single Event Listener
Before we learn about adding multiple event listeners, we need to understand how to add a single event listener.
First, query for the element that you want to add an event listener to by using document.querySelector()
:
JAVASCRIPTconst element = document.querySelector(".element");
Now, simple add an event listener to it. Let's add a simple click listener:
JAVASCRIPTconst element = document.querySelector(".element");
element.addEventListener("click", () => {
console.log("Clicked!");
});
Great, now let's see how we can adapt this to support multiple listeners.
Adding Event Listener to Multiple Elements
In the same way we queried for a single event listener, let's query for multiple event listeners.
This time, let's use document.querySelectorAll()
which returns a list of elements.
JAVASCRIPTconst elements = document.querySelectorAll(".elements");
Now, let's use forEach
to add an event listener to each element:
JAVASCRIPTconst elements = document.querySelectorAll(".elements");
elements.forEach(element => {
element.addEventListener("click", () => {
console.log("Clicked!");
});
});
If you have different elements that you want to add event listeners to, you can first create an array first, then use forEach
on that array.
JAVASCRIPTconst element1 = document.querySelector(".element1");
const element2 = document.querySelector(".element2");
const element3 = document.querySelector(".element3");
const elements = [element1, element2, element3];
elements.forEach(element => {
element.addEventListener("click", () => {
console.log("Clicked!");
});
});
Conclusion
In this post, we've seen how to add a single event listener to an element, and how to add multiple event listeners to multiple elements.
The process is the same, simply query for the element or elements, then add an event listener to each individual element.
Hopefully, this post has helped you get familiar with adding event listeners to elements.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js