The Node.childNodes read-only property returns a live collection of child nodes of the given element where the first child node is assigned index 0.
Syntax
var 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()) {
var children = parg.childNodes;
for (var 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
}
}
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 and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name, etc.).
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
| Specification | Status | Comment |
|---|---|---|
| DOM The definition of 'Node.childNodes' in that specification. |
Living Standard | No change |
| Document Object Model (DOM) Level 3 Core Specification The definition of 'Node.childNodes' in that specification. |
Recommendation | No change |
| Document Object Model (DOM) Level 2 Core Specification The definition of 'Node.childNodes' in that specification. |
Recommendation | No change |
| Document Object Model (DOM) Level 1 Specification The definition of 'Node.childNodes' in that specification. |
Recommendation | Initial definition |
Browser compatibility
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | 1.0 | 20 (12.10240) | 1.0 (1.7 or earlier) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic support | (Yes) | 1.0 | 20 (12.10240) | 1.0 (1.0) | (Yes) | (Yes) | (Yes) |
See also
Document Tags and Contributors
Tags:
Contributors to this page:
DomenicDenicola,
Sebastianz,
jackblackevo,
Robg1,
RonRoyston,
DavidSunny,
pci,
fscholz,
Granjow,
emersion,
ziyunfei,
teoli,
knownasilya,
kscarfone,
Krinkle,
Sheppy,
ethertank,
xni,
LJR,
TTO,
Yaroukh,
Pmash,
Mgjbot,
Ptak82,
GT,
RobG,
Callek,
Phreakazoa,
BenoitL,
Ripter,
Waldo,
Dria,
JesseW
Last updated by:
DomenicDenicola,