Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,767 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,767 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!