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

Natasha Sutevski
Natasha Sutevski
2,557 Points

make listItems refer to a collection

what selector method to use to get all children li of an ul?

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

Steven Parker
Steven Parker
194,902 Points

You made a good choice for the selector method. But the selector argument is the issue.

The final target needs to be the list items (li). And a descendant selector would let you specify the container also to target only the list items in that container.

In case you need a reminder, a descendant selector is created by separating individual selectors for the container and target(s) with a space.