childNodes (W3C DOM Core property)

Tweet

Example

var kids = node.childNodes;

In the example above, kids will be a collection of all the direct child nodes of node. If node has no child nodes then kids will be an empty collection (with zero length). The returned collection is live, which means that changes to the HTML it represents are immediately reflected in the collection, without having to retrieve it again.

So if we say that node is actually an HTML ul element, like this:

<ul>
  <li>Mostly set in 1955 <em>(Part 1)</em></li>
  <li>Mostly set in 2015 <em>(Part 2)</em></li>
  <li>Mostly set in 1885 <em>(Part 3)</em></li>
</ul>

Each of those li elements is a child node of the ul, and will be included in its childNodes collection, numbered 0 to 2. The em elements will not be in that collection, because they’re not direct child nodes of the list (they are descendents, not children).

Note: This example doesn’t take account of whitespace

Actually this example is idealized, and in some browsers there may in fact be additional nodes in the childNodes collection; that’s because some browsers count intermediate whitespace as text nodes, and would therefore consider each piece of whitespace between the structural nodes to be a text node.

For more about this behavior please see DOM Core.

Description

The childNodes collection is an ordered list of all the direct child nodes of this node; if there are no child nodes then this collection is empty (it has zero length). The childNodes collection is a NodeList, in which the items are indexed numerically, and appear in source order.

As with all node lists, childNodes is a live collection, which means that changes to the collection it represents are immediately reflected in the node list (as opposed to it being a static snapshot).

Attributes of an element are not considered child nodes, and therefore don’t appear in the childNodes collection2

This collection is read only.

A collection is not an array

Even though a collection looks like an array, it isn’t an array — although you can iterate through it and refer to its members like an array, you can’t use Array methods like push or pop on it.

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments