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

Kiefer H
Kiefer H
1,820 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.

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];    
<!DOCTYPE html>
    <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>
    <script src="js/app.js"></script>

2 Answers

Kevin Kenger
Kevin Kenger
31,638 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
1,820 Points

Kevin Kenger

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

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


//  secondly, wouldn't this grab everything within the "rainbow" <li> tags?
let listItems = document.getElementById("rainbow");
Kevin Kenger
Kevin Kenger
31,638 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
1,820 Points

I will do that Kevin Kenger

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