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

Chris Sukovich
Chris Sukovich
2,261 Points

Had some fun with EventListeners...

Instead of adding classes to the list items in the HTML, I added a click EventListener to each item inside the for loop so that when clicked it would display a prompt: "Well, what color should it be?", accepts and input, then turns that list item into that color.

Initially, instead of changing to a specific color, I had the click event add the class "NotOrange" which just turned it black, but this was more interesting :)

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

for (let i = 0; i < myList.length; i += 1) {
  myList[i].style.color = 'purple';
  myList[i].addEventListener('click', () => {
    myList[i].style.color = prompt("Well, what color should it be?");                         
  });
}

2 Answers

Steven Parker
Steven Parker
230,231 Points

That's a cute extension on the exercise!

You might be interested to know that another way to do it is to set up a single delegated handler on the list itself, which will then process all of the items in it:

const myUL = document.getElementsByTagName("ul")[0];
myUL.addEventListener("click", e => {
  e.target.style.color = prompt("Well, what color should it be?");
});

Besides only needing one of them, another delegated handler advantage is that it will also respond to any items added later.

Chris Sukovich
Chris Sukovich
2,261 Points

This is a great, concise solution, thank you Steven! Been trying to wrap my head around how to use .target for a while now and this helps me understand it better.