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()

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
18,814 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
rydavim
18,814 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!