In this shot, we will learn how to get the first child of any element. We will discuss the DOM
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.
Let’s try to use the
firstChild property on a
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.
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 using
document.getElementById(), whose first child we want to find. Apply the property
firstChild. It will return the object of the first child and then apply to
innerHTML to get the text inside the element.
In line 15, we will print the text we got from the above step using
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.
View all Courses