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! While you're at it, check out some resources Treehouse students have shared here.
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 trialRebecca Jensen
11,580 PointsLooping through li's to apply EventListener - why can't I just target all li's without looping?
I'm watching a tutorial about Javascript Event Listeners, and the scenario is making text change to upper case on mouseover, and back to lower case on mouse out.
We declare this:
const listItems = document.getElementsByTagName('li')[0];
And these are the functions:
listItems.addEventListener('mouseover', () => {
listItems.textContent = listItems.textContent.toUpperCase();
});
listItems.addEventListener('mouseout', () => {
listItems.textContent = listItems.textContent.toLowerCase();
});
The next step will be to LOOP through each li, so that we can apply this effect to all the li's. However, why doesn't this just work by deleting the [0] that specifies the first li item? Why are we required to loop?
1 Answer
Steven Parker
231,269 PointsA listener can only be added to an element, not an element collection.
If you leave off the index, the getElementsByTagName function returns a element collection. And the *addEventListener" method is found on individual elements, not on collections. So the loop is necessary to attach a listener to each element.
However, you can take advantage of event propagation (also called "bubbling") to create a delegated handler. This would be a single event handler attached to a common parent element which would be triggered by the event "bubbling up" from the child elements. This concept will be explained and illustrated later in the same stage of the course you're taking.