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

Justin Hicks
Justin Hicks
14,290 Points

JavaScript and the DOM events

my question is what would be a good way to change the color of the li in the same manner as we did the toUpperCase and toLowerCase with mouseover or mouseout events the exception being that the event is a click and I want to change the color to what ever is in a text input. Every way I have tried has issues with the adding new items to the list. The below is the best way I've come up with and it still has issues.

colorButton.addEventListener('click', () => {
  const myList = document.querySelectorAll('li');
    for(i = 0; i < myList.length; i += 1) {
      myList[i].style.color = colorInput.value;
} 
});

2 Answers

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,723 Points

Hey Justin,

Your code should work. Here's a link to a jsbin that uses your code to change li to color entered into a textbox:

https://jsbin.com/zijuyamupo/1/edit?html,js,output

Best,

Clayton

Justin Hicks
Justin Hicks
14,290 Points

Yea it does work but I made the mistake of leaving some code out without an explanation. The issue I'm having is that whenever I use an addition text input and button to add additional items to the list, the only time the additional items get the color change is if I click to change the color again. I also cannot have the colorInput.value = ''; at the end of the colorButton click event to clear the colorInput. Those were the issues I'm facing.

Justin Hicks
Justin Hicks
14,290 Points

This is more of the code so you can kinda see what I mean

addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  li.innerHTML = addItemInput.value;
  ul.appendChild(li);
  addItemInput.value = '';
});

removeItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.querySelector('li:last-child');
  ul.removeChild(li);
});  


colorButton.addEventListener('click', () => {
  const myList = document.querySelectorAll('li');
    for(i = 0; i < myList.length; i += 1) {
      myList[i].style.color = colorInput.value;
} 
});