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 JavaScript and the DOM (Retiring) Responding to User Interaction Listening for Events with addEventListener()

Can't figure out what's wrong...

I decided to use a "for... of" loop instead and I can't figure out why my code isn't working:

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

for (let i of listItems) {
  listItems[i].addEventListener('mouseover', () => {
    listItems[i].textContent = listItems[i].textContent.toUpperCase();
  });
}

I keep getting this error in the console: TypeError: listItems[i] is undefined

ywang04
ywang04
6,762 Points

You can use "for of". But the value of i in each iteration of the loop is not index anymore. It should be li element itself. Please refer to the following code:

const listItems = document.getElementsByTagName('li');
for (let i of listItems) {
  i.addEventListener('mouseover',()=>{
      i.textContent = i.textContent.toUpperCase();
  });
  i.addEventListener('mouseout',()=>{
    i.textContent = i.textContent.toLowerCase();
  });
}

2 Answers

Peter Quin
Peter Quin
3,203 Points

'of' should be 'in', so...

for (let i in listItems)

Ahhh, so I can't use "for... of" here? I thought I could since listItems is an array??

Peter Quin
Peter Quin
3,203 Points

Yes you can... yang wangs comment above is the way

thanks yang!!