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.