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

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

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:

// 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:

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:

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:

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 to learn more childNodes and children properties in JavaScript.

✌️ 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.