To get all child nodes of an element, you can use the childNodes
property. This property returns a collection of a node's child nodes, as a NodeList object.
By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.
Let us say you have the following HTML code:
<ul id="langs">
<li>JavaScript</li>
<li>Node</li>
<li>Java</li>
<li>Ruby</li>
<li>Rust</li>
</ul>
The following example selects all child nodes of the <ul>
tag and print their content:
const ul = document.querySelector('#langs');
// get all children
const childern = ul.childNodes;
// iterate over all child nodes
childern.forEach(li => {
console.log(li.innerText);
});
Here is how the output looks like:
undefined
JavaScript
undefined
Node
undefined
Java
undefined
Ruby
undefined
Rust
undefined
Wait, why undefined
appears in the output?
This is because whitespace inside elements is considered as text, and text is treated as nodes. It also applies to comments that are considered as nodes too.
If you want to exclude comment and text nodes, use the children
property instead. This property returns a collection of a node's element nodes only, as an HTMLCollection object:
const children = ul.children;
// iterate over all child nodes
Array.from(children).forEach(li => {
console.log(li.innerText);
});
Here is how the output looks like now:
JavaScript
Node
Java
Ruby
Rust
The difference between
childNodes
andchildren
is thatchildNodes
returns aNodeList
object containing all nodes, including text nodes and comment nodes, whilechildren
returns anHTMLCollection
object only containing element nodes.
To get the first and last children of an element, JavaScript provides firstChild
and lastChild
properties:
const ul = document.querySelector('#langs');
// get first children
const firstChild = ul.firstChild;
// get last children
const lastChild = ul.lastChild;
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.