JavaScript JavaScript and the DOM 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,735 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,199 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,199 Points

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

thanks yang!!