How to get the children of an element using JavaScript

published: 27 Apr 2022

2 min read

How to get the children of an element using JavaScript

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 and children is that childNodes returns a NodeList object containing all nodes, including text nodes and comment nodes, while children returns an HTMLCollection 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;

How to get the children of an element using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming