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

Emil Haroutunian
Emil Haroutunian
8,670 Points

JavaScript and the DOM

I got my answer from another post, but my question is when did the video ever cover what my answer is supposed to be? let listItems = document.querySelectorAll('ul#rainbow > li');

I recall the #. But we never really covered UL being placed before the ID and the >li was never covered either. Did I miss something? Maybe I did, help me out, thanks!

js/app.js
let listItems = document.querySelectorAll('ul#rainbow > li');
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>

1 Answer

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 84,109 Points

I can't say exactly when this was taught, but what you pass into document.querySelectorAll() is the same as a CSS selector. Maybe they assume you've encountered this before in your CSS travels.

FYI, the angle bracket > is the child combinator. I don't see it that often. It targeting only elements that are direct children. More common is just a space (the descendent combinator) which is for any descendants - children, grandchildren, etc. etc.,

In this case it would have worked just fine with the space.

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