HTML DOM firstChild property


The HTML DOM firstChild property is used for returning the first child node of a specific node as a node object. It can return as a text node, element node or a comment node depending on which node is the first. This is a read-only property.

Syntax

Following is the syntax for the HTML DOM firstChild property −

node.firstChild

Example

Let us look at an example for the firstChild property −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script>
   function getFirst() {
      var ch = document.getElementById("DIV1").firstChild.innerHTML;
      document.getElementById("Sample").innerHTML = "The first child node of the div is :"+ch;
   }
</script>
</head>
<body>
<h1>firstChild property</h1>
<div id="DIV1"><p>This is a p element</p><span>This is a span element</span></div>
<button onclick="getFirst()">Get Child</button>
<p id="Sample"></p>
</body>
</html>

Output

This will produce the following output −

On clicking the “Get Child” button −

We have created a <div> element that has a <p> and a <span> element inside it. There is no whitespace inside the div element as the firstChild property considers whitespace as text node and it would make whitespace the first child. In that case it would return undefined.

<div id="DIV1"><p>This is a p element</p><span>This is a span element</span></div>

We have then created the “Get child” button that would execute the getFirst() method when clicked by the user −

<button onclick="getFirst()">Get Child</button>

The getFirst() method gets the first child of the div element using the firstChild property which will return the <p> element in our case. We then get the text inside the p element using the innerHTML property and assigns that value to variable ch. This value is then displayed in the paragraph with id “Sample” by assigning the intended text using innerHTML property −

function getFirst() {
   var ch = document.getElementById("DIV1").firstChild.innerHTML;
   document.getElementById("Sample").innerHTML = "The first child node of the div is :"+list;
}

Updated on: 19-Feb-2021

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements