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 Event Bubbling and Delegation

Loop not working

Hi could someone tell me why this wont work?

If i remove the link and specifiy the li it works fine, but a loop is undicating "myList" does not exist??


<div id="output"> <ol>


<li>Capital testing</li> </ol> </div>


<script type="text/javascript"> var myList = document.getElementsByTagName("li"); for(var i=0;i<myList.length;i++){

myList[i].addEventListener("mouseover",() => {

myList[i].textContent = myList[i].textContent.toUpperCase();


myList[i].addEventListener("mouseout",()=> {

myList[i].textContent = myList[i].textContent.toLowerCase();




1 Answer

Steven Parker
Steven Parker
229,005 Points

The index variable "i" is in global scope, so when the event occurs it is no longer the appropriate value to identify the element. You can fix this by declaring it with "let" instead of "var" which will confine the scope to the loop and give each handier it's own value for "i".

Another (and potentially more elegant) solution would be to make use of the event object that is passed to the handler so it doesn't need to remember which list item it is working with:

    myList[i].addEventListener("mouseover", e => {
      e.target.textContent = e.target.textContent.toUpperCase();

Also, when posting code, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.