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

Chris Glazier
Chris Glazier
5,689 Points

I targeted all the list items and it displays correctly in the preview. Why is this incorrect/less efficient?

Pretty much just want to know why this is incorrect. I copied another way of doing it I found elsewhere and understand why the "correct" one works, I am just confused as why my original answer didn't. Is one way inherently better than the other?

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

for(var i = 0; i < colors.length; i ++) {
  listItems.children[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>
Chris Glazier
Chris Glazier
5,689 Points

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];
}

This is the code that works in the quiz yet they both changed the color of the list items. If someone could tell me the true difference I would love to know, thanks.

1 Answer

Steven Parker
Steven Parker
173,890 Points

Your first example does the job of setting the colors, but the challenge explicitly asked you to "Complete the code by setting the variable listItems to refer to a collection." In the first example, you set "listItems" to refer to a single element. So when the challenge checked the contents of "listItems", it did not contain the correct thing.

In general, you'll get the best results with the challenges by following the instructions carefully and doing only what they ask for.

But if your only objective was to change the colors, there's no significant advantage to either example other than perhaps the name "listItems" (plural) is a bit misleading in the first example and something like "theList" would be a better fit.

Chris Glazier
Chris Glazier
5,689 Points

Alright, makes sense. Thank you for the clarification!

Steven Parker
Steven Parker
173,890 Points

Chris Glazier — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!