How to use DOM firstChild property
Overview
In this shot, we will learn how to get the first child of any element. We will discuss the DOM firstChild property.
The firstChild property, when applied to an element, will return the first child of that element. It will be the same object as other HTML element objects. In many cases, it may return undefined, like when we left spaces before the child element.
Code
Let’s try to use the firstChild property on a div tag.
Explanation
-
In line 5, we have a DIV element with id
elem. Inside the div, we create two 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(). It 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()in which a click will call on the button from the HTML page. -
In line 14, in
function change(), we will get the element usingdocument.getElementById(), whose first child we want to find. Apply the propertyfirstChild. It will return the object of the first child and then apply toinnerHTMLto get the text inside the element. -
In line 15, we will print the text we got from the above step using
console.log().
Output
When we click the button, the console prints First Child, meaning that the property firstChild has returned us the first child of the DIVelement. We then get the inner text of the first child using innerHTML and print it on the console.