Borislav Hadzhiev
Fri Dec 31 2021·2 min read
Photo by Thomas Kelley
To add an event listener to the results from the querySelectorAll
method:
forEach()
method to iterate over the collection of elements.addEventListener()
method on each element in the collection.event type
and a function
to be invoked when the event is
triggered as parameters to the addEventListener
method.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.addEventListener('click', function handleClick(event) { console.log('box clicked', event); box.setAttribute('style', 'background-color: salmon;'); }); });
We used the
document.querySelectorAll
method to select all DOM elements with a class of box
.
The querySelectorAll
method returns a NodeList
, so we are able to use the
NodeList.forEach
method to iterate over the result.
We used the
addEventListener
to add a click
event listener to every element in the collection.
If you need a list of all of the available event types, check out this MDN events list.
Each time the element is clicked we set its background color to salmon
.
An alternative, but also very common approach is to use the for...of
loop to
iterate over the results returned from the querySelectorAll
method.
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.addEventListener('click', function handleClick(event) { console.log('box clicked', event); box.setAttribute('style', 'background-color: salmon;'); }); }
The code snippet above achieves the same result, but this time we used the
for...of
loop to iterate over the NodeList
.
If you need to select elements with different classes, ids, tags, etc, you can
pass multiple, comma-separated selectors to the document.querySelectorAll()
method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box1, .box2, .box3'); boxes.forEach(box => { box.addEventListener('click', function handleClick(event) { console.log('box clicked', event); box.setAttribute('style', 'background-color: salmon;'); }); });
We passed multiple, comma-separated selectors to the querySelectorAll
method
to get a collection of the DOM elements that have a class of box1
, box2
and
box3
.