Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Brian Polonia
25,139 PointsCan event listeners fire on a node list?
Hello,
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
8,947 PointsYou 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
25,139 PointsBrian Polonia
25,139 PointsHa! Makes sense. Thanks so much!