JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Instead of using a loop, couldn't you have used query selector all and then apply the click event on all of these?

I feel like the only reason we are doing a loop is because we only selected one li element. If we selected all, would we not have to worry about the loop?

2 Answers

Steven Parker
Steven Parker
172,127 Points

A NodeList has no method to apply a listener to each of its members, but by looping though them, you can add a listener to each one individually.

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Steven Parker Ah okay so you need to loop through either an HTML collection or a node collection if you are selecting all the elements with li.

Steven Parker
Steven Parker
172,127 Points

Yes, or establish a delegated handler that will cover them all.