Listeners on Multiple Elements
The addEventListener()
method can only be applied to a single target, but it can often be the case that we will want to add an event listener to multiple target elements. To accomplish this we will need to use a loop.
When retrieving multiple elements using the querySelectorAll()
method an array is returned. Using this array and the for...of
statement, it possible to add the same event listener to each element. Additional, by defining the event handler function outside of the addEventListener()
method, we can make the code our more efficient.