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

Blake Baxendell
Blake Baxendell
14,915 Points

Getting console errors, not working after for loop step.

Looked over the video code multiple times. Maybe I'm just not seeing something. Here is my code:

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

for(let i = 0; i < listItems.length; i += 1) {
    listItems[i].addEventListener('mouseover', () => {
        listItems[i].textContent = listItems[i].textContent.toUpperCase();
    });
    listItems[i].addEventListener('mouseout', () => {
        listItems[i].textContent = listItems[i].textContent.toLowerCase();
    });
}

Console Error:

Cannot read property 'toUpperCase' of undefined at HTMLLIElement.listItems.(anonymous function).addEventListener

1 Answer

Steven Parker
Steven Parker
186,663 Points

:point_right: Your code seems fine.

More than that, your code works fine for me. I am not able to reproduce the error. All the list items change case as the mouse passes over them, as expected.

Perhaps there's something elsewhere that is causing the problem. It may require seeing all of the code to identify the issue. You could make a snapshot of your workspace and post the link to it here.

Blake Baxendell
Blake Baxendell
14,915 Points

I refreshed my development area and the errors were gone. Must of been a really bad caching issue on my local development. I refreshed several times and it did not work. A day later, it works.