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

Michael Niers
Michael Niers
7,560 Points

I absolutely don't know how to do this: Complete the code by setting the variable listItems to refer to a collection...

Complete the code by setting the variable listItems to refer to a collection. The collection should contain all list items in the <ul> element with the ID of rainbow.

What do I have to do?

var listItems = documentQuerySelectorAll('li:nth-child()');
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>

2 Answers

Alex Koumparos
Alex Koumparos
Python Web Development Techdegree Student 35,893 Points

Hi Michael,

We can select an element using code like this (let's imagine that the target element had the ID 'select-me'):

var myElement = document.querySelector('#select-me');

Once we have an element selected, we want to select all its children as a single collection. The challenge provides a link to the MDN documentation, the first line of which provides the following example code:

var children = node.children;

Thus we could use this approach with our code from above as follows:

var myElement = document.querySelector('#select-me');
var children = myElement.children;

Since myElement is the same object as document.querySelector('#select-me'), we could replace our reference to the myElement variable with the selector itself and shrink the two lines of code to just one:

var children = document.querySelector('#select-me').children;

Hope that clears things up.



Brendan Whiting
Brendan Whiting
Front End Web Development Techdegree Graduate 84,603 Points

1) You need a period between document and querySelectorAll

2) querySelectorAll needs to start with a lowercase q. There is an object called document and querySelectorAll is a method you call on that object.

3) The argument you need to pass to that method is ul#rainbow li. I'm not sure how you got to li:nth-child(). What they want here is "all list items in the <ul> element with the ID of rainbow.".

Let me know if you need more help.