# How to get the children of an element using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 7, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-get-all-child-nodes-of-an-element

> Learn how to get all child nodes of an element in JavaScript by using the childNodes property of the element.

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](https://attacomsian.com/blog/javascript-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:

```html
<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:

```javascript
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:

```text
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](https://attacomsian.com/blog/javascript-htmlcollection) object:

```javascript
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:

```text
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:

```javascript
const ul = document.querySelector('#langs');

// get first children
const firstChild = ul.firstChild;

// get last children
const lastChild = ul.lastChild;
```
