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.
HTML Code
<!DOCTYPE html> <html> <head> <title>How to get the first child of an element in JavaScript</title> </head> <body> <p id="main">This text is <b>bold</b></p> <script src="app.js"></script> </body> </html>
JavaScript Code: app.js
let element = document.getElementById('main'); let firstChild = element.firstChild; console.log(firstChild.nodeName); console.log(firstChild.textContent); let firstElement = element.firstElementChild; console.log(firstElement.nodeName); console.log(firstElement.textContent);
Output
#text This text is B bold
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.
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.