In this section, we will learn what the Element firstChild property is and how to use it in JavaScript.
What is Element firstChild Property in JavaScript?
The JavaScript Element firstChild property is used to get the first child of an element and it returns a reference of that child-element as a result.
Note: using this property will return the first child no-matter if it’s an Element-Node, Text-Node or a comment-node. But there’s another property called firstChildElement which will return the first child of an element that is an Element-Node! That means for the firstChildElement property, if the first child of an element is in fact of type Text-Node, for example, that will be ignored and instead this property will look for the first occurrence of a child that is an Element-Node.
Element firstChild Property Syntax:
element.firstChild;
Element firstChild Property Input Value
This property is read-only and so it doesn’t accept a value.
Element firstChild Property Return Value
The return value of this property is a reference to the first child of the target element.
Note: the value null will return of the target element doesn’t have a child element.
Example: using firstChild Property in JavaScript
See the Pen using firstChild Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How Does Element firstChild property Work in JavaScript?
Here if you click on the button of the page, the result will be a node of type text! But how? Isn’t it the first element of this list the <li> item?
Well, not exactly! If you look carefully, the first <li> item is set in a newline below the <ol> element. That means first we have a newline character which is a text-node! So technically, the first child of the <ol> is this newline character (which is a text-node).
For this reason, calling the firstChild property gives us this text-node (the newline character) instead of the first <li> element.
Note: you could remove the newline before the first <li> item and in that case this first <li> item becomes the first child of the <ol>.
Example: element firstChild property in JavaScript:
See the Pen element firstChild property in JavaScript by Omid Dehghan (@odchan1) on CodePen.