Node.childNodes read-only property returns a live NodeList of child nodes of the given element where the first child node is assigned index 0.

句法

let nodeList = elementNodeReference.childNodes;
					

范例

简单用法

// parg is an object reference to a <p> element
// First check that the element has child nodes
if (parg.hasChildNodes()) {
  let children = parg.childNodes;
  for (let i = 0; i < children.length; i++) {
    // do something with each child as children[i]
    // NOTE: List is live! Adding or removing children will change the list's `length`
  }
}
					

Remove all children from a node

// 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);
}
					

注意事项

The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties. (For example, to get the name of the first childNode: elementNodeReference .childNodes[1].nodeName )。

document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement . (In (X)HTML documents this is the HTML element.)

childNodes 包括 all child nodes—including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children 代替。

规范

规范 状态 注释
DOM
The definition of 'Node.childNodes' in that specification.
实时标准 无变化
DOM (文档对象模型) 3 级核心规范
The definition of 'Node.childNodes' in that specification.
过时 无变化
DOM (文档对象模型) 级别 2 核心规范
The definition of 'Node.childNodes' in that specification.
过时 无变化
DOM (文档对象模型) 1 级规范
The definition of 'Node.childNodes' in that specification.
过时 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
childNodes Chrome 1 Edge 12 Firefox 1 IE 5 Opera 7 Safari 1.2 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: