dom / latest / node / childnodes.html /

Node.childNodes

The read-only childNodes property of the Node interface 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.

Note: The NodeList being live means that its content is changed each time new children are added or removed.

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, you can use elementNodeReference.childNodes[0].nodeName.

The document object itself has two children: the Doctype declaration and the root element, typically referred to as documentElement. In HTML documents the latter is the <html> element.

It is important to keep in mind that childNodes includes all child nodes, including non-element nodes like text and comment. To get a collection containing only elements, use Element.children instead.

Value

A live NodeList containing the children of the node.

Note: Several calls to childNodes return the same NodeList.

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

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
childNodes
1
12
1
5
7
1.2
1
18
4
10.1
1
1.0

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes