Javascript 遍历子对象的DOM子对象

Javascript 遍历子对象的DOM子对象,javascript,dom,traversal,children,Javascript,Dom,Traversal,Children,为什么元素的子元素的子元素不返回元素,而是给我未定义的元素 let-val; const list=document.querySelector('.collection'); const list items=document.querySelector(“.collection item”); val=list.children; val=val[3].children.children; 控制台日志(val) 。children是一个HTMLCollection,其工作原理

为什么元素的子元素的子元素不返回元素,而是给我未定义的元素

let-val;
const list=document.querySelector('.collection');
const list items=document.querySelector(“.collection item”);
val=list.children;
val=val[3].children.children;
控制台日志(val)

。children
是一个
HTMLCollection
,其工作原理类似于数组。因此,它没有
.children
参数

您需要在数组中循环或选择一项:

val=list.children[0]。children


list.children.forEach(child=>console.log(child.children))
.children
是一个
HTMLCollection
,其工作原理类似于数组。因此,它没有
.children
参数

您需要在数组中循环或选择一项:

val=list.children[0]。children


list.children.forEach(child=>console.log(child.children))

let-val;
const list=document.querySelector('.collection');
const list items=document.querySelector(“.collection item”);
val=list.children;
val=val[2]。子项[0]。子项;
控制台日志(val)

因此,
子项
返回
HTMLCollection
然后在获取新子项时,您必须附加
索引

let-val;
const list=document.querySelector('.collection');
const list items=document.querySelector(“.collection item”);
val=list.children;
val=val[2]。子项[0]。子项;
控制台日志(val)

文档。querySelector('.collection')
是一种返回与包含“collection”CSS类()的任何元素匹配的HtmleElement对象的方法

val=list.children
是一个属性,将返回
list
节点的任何子节点的HTMLCollection(有序集合,即list
由于
children
属性返回一个列表,因此可以使用集合上的
item()
方法或使用数组样式表示法来访问集合中的各个节点。看


最后,;使用
val[3]
调用,请记住JS数组迭代从0开始。要获取val列表/数组中的第三项,可以使用
val[2]

document.querySelector('.collection')
是一个返回与包含“collection”CSS类()的任何元素相匹配的HtmleElement对象的方法

val=list.children
是一个属性,将返回
list
节点的任何子节点的HTMLCollection(有序集合,即list
由于
children
属性返回一个列表,因此可以使用集合上的
item()
方法或使用数组样式表示法来访问集合中的各个节点。看


最后,;使用
val[3]
调用,请记住JS数组迭代从0开始。要获取val列表/数组中的第三项,可以使用
val[2]

.children
属性返回的节点列表/HTML集合,该集合包含parentElement的直接子代(即子元素--不是子元素的子元素)。如果您想使用
.children
访问“孙子辈”,您需要遍历这两个
.children
集合,或者如果您考虑了childElement,则括号表示法将是有效的(例如
parentElement.children[1]
顺便说一句括号表示法中的索引号是基于0的索引,因此例如
。子元素[2]
实际上是第三个元素,依此类推

演示
//参考
    const list=document.querySelector('.list'); /* 然后将
      中的每个
    • 收集到一个NodeListr中 使用括号和 扩展运算符(即[…节点列表] *///itemsA和itemsB是相同的 const itemsA=[…list.querySelectorAll('.item')]; const itemsB=[…list.children]; /* 由于OP目标不明确……以下是验证结果的控制台日志。 最后一个控制台日志是我对OP目标的最好猜测。 */ console.log(`.list直接子体(也称为子体):\n ${itemsB.map(item=>`…\n`)}`); console.log(`Array itemsA(作为htmlString):\n ${itemsA.map(item=>item.outerHTML)}`); console.log(`Array itemsB(作为htmlString):\n ${itemsB.map(item=>item.outerHTML)}`); console.log(`Third.item of.list(作为htmlString):\n ${itemsA[2].outerHTML}`); console.log(`Third.item of.list最深的子代:\n ${[…itemsB[2].children].flatMap((节点,索引)=>node.children[index].outerHTML)}`);
.list{
列表样式:无
}
.项目{
边际下限:14px
}
.作为控制台包装{
宽度:375px;
最小高度:100%;
左边缘:25%;
}
.作为控制台行{
边框底部:5px山脊#333
}
.as控制台行代码::第一行{
文字装饰:下划线;
}
.作为控制台行。作为控制台行::之后,
.作为控制台行代码。作为控制台行代码::之后{
内容:'';
填充:0;
保证金:0;
边界:0;
宽度:0;
}