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.
Lets try to use the firstElementChild
property on a div tag.
In line 5, We have a div
element with id = elem
, and inside the div
we 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 the HTML
page.
In line 14, in the change()
function, we will get the parent div element using document.getElementById()
, whose first element child we want to find. Apply the property firstElementChild
, and it will return the object of the first element child. Then, apply innerHTML
to get the text inside the element. We will print the text we got from the above step using console.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.