HTML DOM Element childNodes

Example

Get the <body> element's child nodes:

const nodeList = document.body.childNodes;
Try it Yourself »

Get the number of child nodes in "myDIV":

let numb = document.getElementById("myDIV").childNodes.length;
Try it Yourself »

More examples below.


Description

The childNodes property returns a collection (list) of an elements's child nodes.

The childNodes property returns a NodeList object.

The childNodes property is read-only.

childNodes[0] is the same as firstChild.

Important!

childNodes returns nodes: Element nodes, text nodes, and comment nodes.

Whitespace between elements are also text nodes.

Alternative:

The children Property

The children property returns elements (ignores text and comments).

See Also:

The firstChild Property

The lastChild Property

The nextSibling Property

The previousSibling Property

The hasChildNodes() Method

Node Properties

The parentNode Property

The nodeName Property

The nodeType Property

The nodeValue Property

HTML Nodes vs Elements

In the HTML DOM (Document Object Model), an HTML document is a collection of nodes with (or without) child nodes.

Nodes are element nodes, text nodes, and comment nodes.

Whitespace between elements are also text nodes.

Elements are only element nodes.


childNodes vs children

childNodes returns child nodes (element nodes, text nodes, and comment nodes).

children returns child elements (not text and comment nodes).


Siblings vs Element Siblings

Siblings are "brothers" and "sisters".

Siblings are nodes with the same parent (in the same childNodes list).

Element Siblings are elements with the same parent (in the same children list).



Syntax

element.childNodes

Return Value

Type Description
ObjectA NodeList object collection of nodes.
The nodes are sorted as they appear in the document.

More Examples

Change the background color of the second child node:

element.childNodes[1].style.backgroundColor = "yellow";
Try it Yourself »

Get the text of the third child node of a <select> element:

let text = document.getElementById("mySelect").childNodes[2].text;
Try it Yourself »

Browser Support

element.childNodes is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.