Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Brian Polonia
Brian Polonia
25,139 Points

Can event listeners fire on a node list?


Can I have an event listener fire on a node list?

For example lets say I have 3 inputs with class of "first" and I add an event listener using getElementsByClassName('first');, will the function passed to the event listener fire on any of those elements?

I am trying it and it isn't working, but it does work if I specify which item from the node list to fire on. For example, if I select the first item from the node list like so, getElementsByClassName('first')[0]; then it works.

1 Answer

Niclas Valentiner
Niclas Valentiner
8,947 Points

You can put the same event listener on all of the elements, just run through them in a loop. A simple for loop fixes it all but I'd recommend storing all the elements in a variable, like so:

var inputs = window.getElementsByClassName('first');

for( var i = 0 ; inputs.length < i ; i++ ) {
    //Add event listener to inputs[i] here
Brian Polonia
Brian Polonia
25,139 Points

Ha! Makes sense. Thanks so much!