Get the first Child of specific Type using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 3, 2022

banner

Check out my new book

Get the first Child of specific Type using JavaScript #

Use the querySelector() method to get the first child of specific type, e.g. document.querySelector('#parent > p:first-of-type'). The method returns the first element that matches the selector. If no element matches the provided selector, null is returned.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <p>Child 1</p> <p>Child 2</p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// ✅ Get first direct child with type P const p1 = document.querySelector('#parent > p:first-of-type'); console.log(p1); // 👉️ <p>Child 1</p> // ✅ Get first direct or indirect child with type P const p1Again = document.querySelector( '#parent p:first-of-type' ); console.log(p1Again); // 👉️ <p>Child 1</p>

We used the document.querySelector method to get the first child of the div with id of parent that has a type of p.

The querySelector method takes a valid CSS selector as parameter and returns the first element that matches.

The :first-of-type pseudo-class represents the first element of its type among a group of siblings.

In the first example, we look for a direct child that has a type of p.

index.js
const p1 = document.querySelector('#parent > p:first-of-type');

This wouldn't work if we had a nested p in the div, for example:

index.html
<div id="parent"> <span> <p>Child 1</p> </span> <span> <p>Child 2</p> </span> </div>
Since the p elements are nested inside of a span, our first selector would not match an element and would return a null value.

Our second example however, matches the first p element that it finds anywhere in the div element with id of parent.

index.js
const p1Again = document.querySelector( '#parent p:first-of-type' ); console.log(p1Again); // 👉️ <p>Child 1</p>

The code snippet would work even if the p element was nested.

Use the search field on my Home Page to filter through my more than 3,000 articles.