JavaScript JavaScript and the DOM Getting a Handle on the DOM Selecting Multiple Elements

The for loop cycles over list items and applies a color to each item using the values stored in the colors array.

The for loop cycles over list items and applies a color to each item using the values stored in the colors array. HELP

js/app.js
var listItems;
var colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

for(var i = 0; i < colors.length; i ++) {
  listItems[i].style.color = colors[i];    
}
index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Rainbow!</title>
  </head>
  <body>
    <ul id="rainbow">
      <li>This should be red</li>
      <li>This should be orange</li>
      <li>This should be yellow</li>
      <li>This should be green</li>
      <li>This should be blue</li>
      <li>This should be indigo</li>
      <li>This should be violet</li>
    </ul>
    <script src="js/app.js"></script>
  </body>
</html>

3 Answers

Alex Koumparos
MOD
Alex Koumparos
Python Web Development Treehouse Moderator 33,475 Points

The challenge is specifically testing the ability to work with a collection using the concept of children. As such, to pass the challenge you need to explicitly select the li elements that are children of the ul with the id "rainbow". Here is the clue text from the challenge:

The collection should contain all list items in the <ul> element with the ID of rainbow.

We can do this by selecting the element with the specified id, and then modifying that selection to refer to its children:

var listItems = document.getElementById('rainbow').children;

Cheers,

Alex

Cameron Sprague
Cameron Sprague
8,529 Points

Just in case anyone else is still finding this thread here is the full JavaScript code below.

var listItems = document.getElementById('rainbow').children;
var colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

for(var i = 0; i < colors.length; i ++) {
  listItems[i].style.color = colors[i];    
}

Best, Cameron Sprague

Linas Mackonis
Linas Mackonis
6,721 Points

Hi mo,

Your code should look like this:

var listItems = document.getElementsByTagName('li');
var colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

for(var i = 0; i < colors.length; i ++) {
  listItems[i].style.color = colors[i];    
}

Thanks. But I have to say THIS IS VERY HARD. HTML check CSS check JavaScript HELP!

dahmeethook
dahmeethook
7,165 Points

@Linas Mackonis, the code you've shared above was not acceptable in the treehouse system. I tried to solve this on my own and couldn't.