JavaScript JavaScript and the DOM Getting a Handle on the DOM Using CSS Queries to Select Page Elements

We have some JavaScript code that will cycle over list items and apply colors from an array called colors. The code will

Hi,

please help with this quiz. I've wrtitten this code: '''let listItems = document.getElementsByTagName('ul'); '''

but it tells ms it's wrong! What am I wrong?

Thanks

4 Answers

Tijo Thomas
Tijo Thomas
9,737 Points

If you watch the previous video you learn about the .querySelector() and .querySelectorAll() methods. In this case you want to use .querySelectorAll() and the code should look like this:

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

Just a note, when trying to post code snippets in the forum you need to use backticks and not apostrophes in order for the code to be formatted. The backtick key is should be to the left of the "1" key on your keyboard. For proper syntax highlighting you need to specific the language of the code after the first 3 backticks. Here is a link that shows what I mean. Just scroll down to the Inline code and block code section.

On the examples of the video it didn't mention that we had to add the li tag after id. Why now is a MUST to add li after id. Its only one id= "rainbow" on the index.html???? Or only on querySelector() it's not necessary??

Christina Freyhult
Christina Freyhult
Front End Web Development Techdegree Student 9,565 Points

I agree with Eni, the video does not get that specific. He only ever shows the example of the id.

Is it wrong to use document.getElementsByTagName??

Ryan Mayo
Ryan Mayo
12,631 Points

document.getElementsByTagName() works fine Luca, but you'd have to use it on the li tag, not on the ul tag. That is how I was able to accomplish the test.

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 86,643 Points

What you want to do is target a specific element.

In JS you can target elements in the same way as you would with CSS by using query selector. You want to target the list items inside the unordered list with the #id rainbow.

document.querySelectorAll("#rainbow li");