如何获取子数据 javascript

How to get childs data javascript

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

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>

这里的问题是子节点不仅returns elements. There are also nodes without a style attribute. As example between the html tags there are empty text nodes。如果在 for 循环中添加 console.log(toolbarForChilds.childNodes[i]);,您应该会在浏览器控制台中看到它。

您的代码不起作用的原因是 childNodes 还包括元素之间的换行符。您可以 console.log childNodes 来查看它们。如果您将代码包装在 try-catch 中以跳过这些代码,您的代码将起作用,尽管您应该遵循 Mamun 的回答以获得更简洁的方法。

for (let i = 0; i < toolbarForChilds.childNodes.length; i++) {
    try {
      toolbarForChilds.childNodes[i].style.cursor = "default";
    }
    catch {
        continue;
    }
}

node.childNodes returns 没有样式属性的元素,如文本节点。对于仅获取节点元素,即 div 的:id ="title" & id ="another thing" 使用 node.children。下面实现。

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