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

Christopher Evans
Christopher Evans
7,032 Points

Can only turn the list items orange, can't cycle through all colours.

It's in the title - what am I doing wrong to prevent my code looping through all colours?

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

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

1 Answer

53,537 Points

With document.querySelectorAll("ul") you are selecting the unordered list instead of the list items. Since there is only one ul your loop assigns the list the first color when i = 0 but for i greater than 0 listItems[i] is undefined and an error is generated. To resolve select the list items instead.