Node.childNodes - Web APIs 编辑

The 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. Child nodes include elements, text and comments.

Syntax

let nodeList = elementNodeReference.childNodes;

Examples

Simple usage

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

Notes

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[0].nodeName.)

The 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 includes all child nodes—including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.childNodes' in that specification.
Living StandardNo change
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.childNodes' in that specification.
ObsoleteNo change
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Node.childNodes' in that specification.
ObsoleteNo change
Document Object Model (DOM) Level 1 Specification
The definition of 'Node.childNodes' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:125 次

字数:4731

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文