简体   繁体   English

在javascript中按ID选择UL

[英]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. 我正在做树屋JavaScript轨道,我给了一个目标,我无法弄清楚如何通过。 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. 目标:在app.js的第1行,设置变量listItems以引用集合。 The collection should contain all list items in the unordered list element with the id of rainbow. 该集合应包含无序列表元素中的所有列表项,其id为rainbow。

For app.js you are given: 对于app.js,您将获得:

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. 在index.html里面,我们指的是如下。

<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') TypeError:'undefined'不是对象(评估'listItems [i] .style')

Special note: This cannot be jquery it must be javascript. 特别说明:这不能是jquery必须是javascript。

#rainbow refers to the unordered list, not the list items themselves. #rainbow指的是无序列表,而不是列表项本身。 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. 传递给querySelectorAll方法的选择器与编写CSS选择器的方式相匹配:您正在收集与该选择器匹配的所有元素,并且收集该选择器。 The selector #rainbow li may be a little bit greedy, too, in that it will select all li s that are descendants of the #rainbow element, not just the children . 选择器#rainbow li也可能有点贪心,因为它会选择所有作为#rainbow元素后代li ,而不仅仅是元素。 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. 如果querySelectorAll给出了你没有明确要求的元素,我会说这是一个破碎的方法。

The array of colors could have more elements than the listItems array. 颜色数组可以包含比listItems数组更多的元素。 So, when i variable is greater than the size of the listItems array - 1, you receive a TypeError. 因此,当i变量大于listItems数组的大小 - 1时,您会收到TypeError。 And of course, you have to select the items inside the ul and not the ul itself. 当然,您必须选择ul内的项目而不是ul本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM