Select UL by ID in javascript
I am doing a JavaScript track on a tree and I am given a target so that I cannot figure out how to get through. I don't understand why the code I wrote won't work.
Purpose. On line 1 of the app.js application, set the listItems variable to reference the collection. The collection must contain all the list items in an unordered list item with a rainbow ID.
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 linking to looks like this.
<ul id="rainbow">
So, I think I should do this:
let listItems = document.querySelectorAll('#rainbow');
But when I do this I get the error
TypeError: 'undefined' is not an object (evaluate 'listItems [i] .style')
Special note: this cannot be jquery, it must be javascript.
source to share
#rainbow
refers to an unordered list, not list items. You need to change your selector to include list items:
let listItems = document.querySelectorAll('#rainbow li');
Explanation
The selector passed to the method querySelectorAll
corresponds to the way a CSS selector is written: you collect all the elements that match that selector, and only that selector. The selector #rainbow li
can be a little greedy, as it will select everyone li
that is descendant of the element #rainbow
, not just children . To select only children you could write:
let listItems = document.querySelectorAll('#rainbow > li');
// or, more verbose...
let rainbow = document.querySelectorAll('#rainbow');
let listItems = rainbow.children;
If you were querySelectorAll
displaying items that you did not explicitly ask for, I would say it is a broken method.
source to share