gpt4 book ai didi

javascript - 如何获取 child 的数据JavaScript

转载 作者:行者123 更新时间:2023-12-03 08:05:50 25 4
gpt4 key购买 nike

有人可以向我解释我做错了什么吗?

let toolbarForChilds = document.getElementById("toolbar");

for (let i = 0; i < toolbarForChilds.childNodes.length; i++) {
toolbarForChilds.childNodes[i].style.cursor = "default";
}
<div class="sample-toolbar" id="toolbar" style="text-align: center;">
<div id="title">#1</div>
<div id="another thing">#2</div>
</div>


我在控制台中收到此错误:
Uncaught TypeError: Cannot set property 'cursor' of undefined

最佳答案

Node.childNodes

childNodes includes all child nodes—including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.



您不需要使用 childNodes。您可以使用 querySelectorAll()定位所有元素,并按以下方式遍历它们:

let toolbarForChilds = document.querySelectorAll("#toolbar div");

for (let i = 0; i < toolbarForChilds.length; i++) {
toolbarForChilds[i].style.cursor = "default";
}
<div class="sample-toolbar" id="toolbar" style ="text-align: center;">
<div id ="title">#1</div>
<div id ="another thing">#2</div>
</div>

关于javascript - 如何获取 child 的数据JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60688872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com