Adding Event Listeners to Elements Returned from querySelectorAll
In this blog post, we will discuss how to add event listeners to all the elements returned by a document.querySelectorAll()
call. This method allows us to iterate over the results and attach an event listener to each element.
By using the for..of
loop, we can easily iterate over the NodeList returned by querySelectorAll()
. Here’s an example:
1 | const buttons = document.querySelectorAll("#select .button"); |
It is worth noting that document.querySelectorAll()
does not return an array. Instead, it returns a NodeList object. However, you can still iterate over it using the forEach
method or the for..of
loop.
If you prefer working with an array, you can transform the NodeList into an array using the Array.from()
method. For example:
1 | const buttonsArray = Array.from(buttons); |
Using the above techniques, you can easily add event listeners to all elements returned by querySelectorAll()
and perform any desired actions.
Tags: JavaScript, DOM, Event listeners, querySelectorAll