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

Obe Juarez
Obe Juarez
5,903 Points

Console throws error

My console is telling me : Cannot read property 'toUpperCase' of undefined and nothing is happening when i mouse over

for (let i = 0; i < listItems.length; i++) {

  listItems[i].addEventListener('mouseover', () => {
    listItems[i].textContent = listItems.textContent.toUpperCase();
  });
  listItems[i].addEventListener('mouseout', () => {
    listItems[i].textContent = listItems.textContent.toLowerCase();
  });

 }

Mod Edit: Fixed code for readability. See the markdown guide for how to do fancy code blocks.

rydavim
rydavim
Treehouse Moderator 18,641 Points

It would be helpful to see a workspace snapshot that includes the rest of your code. It looks like the error may not be coming from that block, but I'm not sure.

1 Answer

rydavim
MOD
rydavim
Treehouse Moderator 18,641 Points

Thanks for the additional info! So in your snapshot, it looks like you haven't defined listItems - so I'm actually a little bit surprised at the error you're getting.

// assuming you've got something like this, you should be okay...
const listItems = document.getElementsByTagName('li');

Your loop actually looks pretty good - you've only got one minor issue. You are setting the textContent equal to itself, but with capital letters. That means you need to include the index on both sides of the expression.

for (let i = 0; i < listItems.length; i++) {
  listItems[i].addEventListener('mouseover', () => {
    listItems[i].textContent = listItems.textContent.toUpperCase(); // listItems[i] on both sides
  });
  listItems[i].addEventListener('mouseout', () => {
    listItems[i].textContent = listItems.textContent.toLowerCase(); // and again here
  });
 }

Otherwise your code looks good, but let me know if you're still running into issues and we can work through a solution together. Nice work, and happy coding!