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

Jennifer Lipps
Jennifer Lipps
3,221 Points

Why am I getting "typeError undefined is not an object" here?

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

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

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

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

Piotr Manczak
Piotr Manczak
Front End Web Development Techdegree Student 16,079 Points

you could use:

var listItems = document.getElementsByTagName('li');

I checked, it worked. using #rainbow you are targeting <ul> instead of <li>.

Tobiasz Gala
Tobiasz Gala
Full Stack JavaScript Techdegree Student 21,096 Points

querySelector and querySelectorAll is using CSS-like selectors to select elements on the page

document.querySelectorAll('#rainbow li');  // select li elements within id of rainbow