# How to get first and last 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-first-and-last-children-of-an-element

> Learn how to use firstChild and lastChild element properties to get the first and last child nodes of an HTML element in JavaScript.

To get the first child node of an HTML element, you can use the `firstChild` property. This property returns a node's first child, as a `Node` object.

Let us say you have the following HTML code snippet:

```html
<ul id="langs">
    <li>JavaScript</li>
    <li>Node</li>
    <li>Java</li>
    <li>Ruby</li>
    <li>Rust</li>
</ul>
```

The following example selects the first `<li>` element by using the `firstChild` property:

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

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

console.log(first.innerText);
```

You might encounter a weird behavior with `firstChild` if there is whitespace between the parent node and the first child node.

For example, the above code snippet might print `undefined` on the console. This is because whitespace inside elements is considered as text, and text is considered as nodes.

One way to handle this situation is to remove all whitespace between elements. Alternatively, you could use the `firstElementChild` property that ignores whitespace and comments, and returns the first element node:

```javascript
// get first element node
const first = ul.firstElementChild;

console.log(first.innerText); // JavaScript
```

To return the last child node of a specified node, use the `lastChild` property:

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

// get last child
const last = ul.firstChild;

console.log(last.innerText);
```

Similarly, there is another property called `lastElementChild` to get the last element node by ignoring all whitespace and comments:

```javascript
const last = ul.lastElementChild;

console.log(last.innerText); // Rust
```

If you want to get all child nodes of an element, use the `childNodes` or `children` property:

```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);
});
```

Take a look at [this article](https://attacomsian.com/blog/javascript-dom-get-all-child-nodes-of-an-element) to learn more `childNodes` and `children` properties in JavaScript.
