What is the DOM firstElementChild Property?
Overview
In this shot, we will learn how to get the first element child of any parent element. We will discuss the DOM firstElementChild property.
The firstElementChild property, when applied to the element, will return the first element child of that element, unlike the property firstChild, which returns the first child that includes text. Regardless, firstElementChild will return the first element in that parent node.
Code
Lets try to use the firstElementChild property on a div tag.
Explanation
-
In line 5, We have a
divelement withid = elem, and inside thedivwe are creating 2 paragraph child elements. -
In line 8, we have a paragraph tag for displaying text.
-
In line 10, we have written a button tag with a function
change(), which will be called when the user clicks on it. -
In line 13, we have written the JavaScript code in the script tag. We have defined a function
change(), where the click will call the button from theHTMLpage. -
In line 14, in the
change()function, we will get the parent div element usingdocument.getElementById(), whose first element child we want to find. Apply the propertyfirstElementChild, and it will return the object of the first element child. Then, applyinnerHTMLto get the text inside the element. We will print the text we got from the above step usingconsole.log().
When we press the button, the console displays the text “First Element child”, indicating that the property firstElementChild has returned the div element’s first element child.