Search code examples
javascriptcss-selectorsselectors-api

Select UL by ID in javascript


I am doing the treehouse JavaScript track and am given an objective that I cannot figure out how to pass. I don't see why the code I have written won't work.

The Objective: On line 1 of app.js, set the variable listItems to refer to a collection. The collection should contain all list items in the unordered list element with the id of rainbow.

For app.js you are given:

let listItems;
const colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

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

Inside index.html the line we are referring to is as follows.

<ul id="rainbow">

So I would think that I should be able to do this:

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

But when I do that I get the error

TypeError: 'undefined' is not an object (evaluating 'listItems[i].style')

Special note: This cannot be jquery it must be javascript.


Solution

  • #rainbow refers to the unordered list, not the list items themselves. You need to change your selector to include the list elements:

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

    Explanation

    The selector passed to the querySelectorAll method matches the way you would write a CSS selector: you are gathering all elements that match that selector and only that selector. The selector #rainbow li may be a little bit greedy, too, in that it will select all lis that are descendants of the #rainbow element, not just the children. To select only the children you could write:

    let listItems = document.querySelectorAll('#rainbow > li');
    
    // or, more verbose...
    let rainbow = document.querySelectorAll('#rainbow');
    let listItems = rainbow.children;
    

    Had querySelectorAll given back elements that you weren't explicitly asking for, I'd say that's a broken method.