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;

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.