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

Rebecca Jensen
Rebecca Jensen
11,568 Points

Looping 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
Steven Parker
186,663 Points

A 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.