JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get the first child of an element in JavaScript?

To get the first child of an HTML element, JavaScript DOM provides two properties, firstChild, and firstElementChild.

The firstChild property returns the first child node of an element. The child node returned by this property can be a text node, an element node, or a comment node.

The firstElementChild property only returns the child node, which is the element node. It does not return text and comment nodes.


<!DOCTYPE html>
  <title>How to get the first child of an element in JavaScript</title>
  <p id="main">This text is <b>bold</b></p>
  <script src="app.js"></script>

JavaScript Code: app.js

let element = document.getElementById('main');
let firstChild = element.firstChild;

let firstElement = element.firstElementChild;


This text is 

The DOM tree representation of the paragraph element is shown in the following image that clarifies which element is the first child node and the first child element.

DOM tree representation of paragraph

In this code, you can see that the firstChild property has returned the text node. On the other hand, the firstElementChild property has returned the element node.

Recommended Posts