childNodes property
The childNodes property stores a
pseudo-array
of the element's child nodes (tags,
comments and text nodes).
Syntax
element.childNodes;
Example
We get all child nodes of an element and display their content:
<div id="parent">text<p>parag</p><!--com--></div>
let parent = document.querySelector('#parent');
let nodes = parent.childNodes;
for (let node of nodes) {
console.log(node.textContent);
}
Example
Display a contents of the first node:
<div id="parent">text<p>parag</p><!--com--></div>
let parent = document.querySelector('#parent');
console.log(parent.childNodes[0].textContent);
The code execution result:
'text'
Example
Let's display the contents of
the node with the number 2:
<div id="parent">text<p>parag</p><!--com--></div>
let parent = document.querySelector('#parent');
console.log(parent.childNodes[2].textContent);
The code execution result:
'com'
See also
-
the
childrenproperty
that contains child elements -
the
firstChildproperty
that contains the first node -
the
lastChildproperty
that contains the last node