How to get the first child of a parent DOM element in JavaScript?

October 6, 2020 - 1 min read

To get the first child of a parent element, you can use the firstElementChild property in the DOM element in JavaScript.

Let's say we have a parent element div and three paragragh tags inside it like this,

<div id="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
</div>

Now let's get the first paragraph element from the div tag.

To get the first paragragh element, first we have to get a reference to the div tag and then use the firstElementChild property like this,

// get refernece to tht div tag
const div = document.querySelector("#container");

// ge the first child element
const firstChild = div.firstElementChild;

console.dir(firstChild); // first p tag properties and methods

See this example live in JSBin.

Feel free to share if you found this useful 😃.