Get the first Child of specific Type using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

banner

Photo by Hannah Busing

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee