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()
:
const element = document.querySelector(".element");
Now, simple add an event listener to it. Let's add a simple click listener:
const 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.
const elements = document.querySelectorAll(".elements");
Now, let's use forEach
to add an event listener to each element:
const 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.
const 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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!