有人可以向我解释我做错了什么吗?
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
最佳答案
childNodes
includes all child nodes—including non-element nodes like text and comment nodes. To get a collection of only elements, useParentNode.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/