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

Can someone help me with this question?


<!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>
let listItems = document.querySelector("#rainbow");
const colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

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

1 Answer

David McNeill
David McNeill
44,420 Points

Hi again!

You just need to change two small things in your code.

let listItems = document.querySelectorAll("#rainbow li");

Changing querySelector to querySelectorAll will return a collection for your for loop. You also need to adjust the selector used from ("#rainbow") to ("#rainbow li").

In your answer you were just selecting the <ul> element, which is not what the challenge was asking. You need to select all of the <li> elements within the <ul>. The code above achieves that using a descendant selector ("#rainbow li"), something you might know from CSS.