Node: childNodes 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Node 接口的只读 childNodes 属性返回一个实时的 NodeList,其中包含给定元素的子 节点,第一个子节点索引为 0。子节点包括元素、文本和注释。

注意: 实时 NodeList 意味着每次添加或删除新子节点时,其内容都会发生更改。

浏览器会将文本节点插入文档以表示源代码标记中的空格。因此,例如使用 Node.childNodes[0] 获取的节点可能指向一个空格文本节点,而不是作者 intended 获取的实际元素。

有关更多信息,请参阅 DOM 中的空格处理

集合中的节点是对象,而不是字符串。要从节点对象获取数据,请使用它们的属性。例如,要获取第一个 childNode 的名称,可以使用 elementNodeReference.childNodes[0].nodeName

document 对象本身有两个子节点:Doctype 声明和根元素,通常称为 documentElement。在 HTML 文档中,后者是 <html> 元素。

请记住,childNodes 包括所有子节点,包括非元素节点,如文本和注释。要获取仅包含元素的集合,请使用 Element.children

一个包含节点子节点的实时 NodeList

注意:childNodes 的几次调用返回的是同一个 NodeList

示例

简单用法

js
// Note that para is an object reference to a <p> element

// First check that the element has child nodes
if (para.hasChildNodes()) {
  let children = para.childNodes;

  for (const node of children) {
    // Do something with each child as children[i]
    // NOTE: List is live! Adding or removing children will change the list's `length`
  }
}

移除节点的所有子节点

js
// This is one way to remove all children from a node
// box is an object reference to an element
while (box.firstChild) {
  // The list is LIVE so it will re-index each call
  box.removeChild(box.firstChild);
}

规范

规范
DOM
# ref-for-dom-node-childnodes①

浏览器兼容性

另见