HTML DOM Element childNodes attribute

Definition and Usage

childNodes The attribute returns a collection (list) of element child nodes.

childNodes The attribute returns a NodeList object.

childNodes The attribute is read-only.

childNodes[0] Same as firstChild.

Tip

childNodes Returns the node: element node, text node, and comment node.

Whitespace between elements is also a text node.

Alternative:

children attribute - children The attribute returns the child elements (ignoring text and comments).

See also:

firstChild attribute

lastChild attribute

nextSibling attribute

previousSibling attribute

hasChildNodes() method

Node attribute

parentNode attribute

nodeName attribute

nodeType attribute

nodeValue attribute

HTML nodes and elements

in HTML DOM(Document Object Model), an HTML document is a collection of nodes (or not) that have (or do not have) child nodes.

Noderefers to element nodes, text nodes, and comment nodes.

Elementwhitespace between them is also a text node.

while elements are just element nodes.

Child nodes and child elements

childNodes ReturnsChild nodes(element nodes, text nodes, and comment nodes).

children ReturnsChild elements(not text and comment nodes).

Siblings and element siblings

Siblingsare 'brothers' and 'sisters'.

Siblingsare nodes that have the same parent node (in the same childNodes in the list).

Element siblingsare elements that have the same parent element (in the same children in the list).

Example

Example 1

Get the child nodes of the <body> element:

const nodeList = document.body.childNodes;

Try It Yourself

Example 2

Get the number of child nodes in "myDIV":

let numb = document.getElementById("myDIV").childNodes.length;

Try It Yourself

Example 3

Change the background color of the second child node:

element.childNodes[1].style.backgroundColor = "yellow";

Try It Yourself

Example 4

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

let text = document.getElementById("mySelect").childNodes[2].text;

Try It Yourself

Syntax

element.childNodes

Return Value

Type Description
Object

The NodeList object collection of nodes.

Nodes are sorted in the order they appear in the document.

Browser Support

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

All browsers fully support it:

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