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) Getting a Handle on the DOM Selecting Multiple Elements

Kiefer H
Kiefer H
5,665 Points

For Loop only changes text to red

I don't know how to get this to select the whole 'colors'.

I figured it out yesterday, but i knew it was fluke and now i cannot reproduce it.

js/app.js
let listItems = document.querySelectorAll('#rainbow');
var colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

for(var i = 0; i < listItems.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>

2 Answers

Kevin Kenger
Kevin Kenger
32,834 Points

Hey Kiefer,

I'll admit the verbiage of the challenge is a little confusing, but it's asking you to select all of the elements within the #rainbow, not the #rainbow element itself.

Try adding the li selector after:

let listItems = document.querySelectorAll('#rainbow li');
Kiefer H
Kiefer H
5,665 Points

Kevin Kenger

Is there a reason why the code below wouldn't work?

// does this not grab the "rainbow" tag in the <li>?

document.querySelector("li.rainbow");

//  secondly, wouldn't this grab everything within the "rainbow" <li> tags?
let listItems = document.getElementById("rainbow");
Kevin Kenger
Kevin Kenger
32,834 Points

The first would select all li elements with the class of rainbow.

The second would select only the ul element with the id of rainbow, not its child elements (the lis you're trying to loop over).

If you haven't already checked out the CSS Selectors course, you should. It will definitely help with your JavaScript development, as well as any other frontend development you might be interested in.

Kiefer H
Kiefer H
5,665 Points

I will do that Kevin Kenger

I am on the FullStack JS Track. I'll take some time and do the CSS Selectors.