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 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
217,532 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.