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

Mareks Zevalds
Mareks Zevalds
2,997 Points

TypeError on retrieving a list item from querySelectorAll.

Hey all!

I am not sure what is going on, but I get a TypeError on listItems[i]. I can't really understand what is the issue via the console as it covers the whole page. Can someone please advise on what is the issue with the code? I played around with querySelectorAll and it should just give a list, but it does not in the console...

const 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];    
<!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>
Mareks Zevalds
Mareks Zevalds
2,997 Points

Note: this is from the code challenge. It wasn't written in the workspace.

1 Answer

Try : document.querySelectorAll('#rainbow li'); You currently only selecting the ul not the list items.