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 trial

JavaScript

Getting error listItems.addEventListener is not a function

I think I've done exactly as Gil in the video, but I'm getting a console error and breaking other eventlisteners on the page when this code is added. What little detail am I missing?

const listItems = document.getElementsByTagName('li');

listItems.addEventListener('mouseover', () => { listItems.textContent = listItems.textContent.toUpperCase(); });

listItems.addEventListener('mouseout', () => { listItems.textContent = listItems.textContent.toLowerCase(); });

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The listItems holds a collection of list items, not just one list item. You cannot add an eventListener onto a collection. You need to loop over the collection and add the eventListener to each individual item.

At 5:20 of this video you can see that he has const listItems = document.getElementsByTagName('li')[0];. This selects the first list item and no more. But yours selects all list items.

At 5:54 he removes the [0] to select the entire collection of list items. Around 6:28 he starts implementing the for loop to iterate over the collection and add the eventListener to each individual list item.

Hope this helps! :sparkles:

Got it, thanks! I noticed that just as I moved on in the video (argh!). Maybe there should be a "delete question" option for the site, as I'm sure many folks have an "aha" just as they press "post." :) thanks again

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

There actually is, but it requires that no one has answered :smiley: That being said, these questions and their answers spark some really fascinating discussions sometimes with multiple ways of solving things and excellent resources. It would be a shame to remove anything that could help others learn :sparkles: