The DOM firstChild Property is used to return the firstchild Node of its parent node element. It is read-only property and may return an element node, a text node or a comment node.Â
Syntax
node.firstChild Return Value: It returns a string value which represent the first child of a node. If the element does not have a child node then it returns a null value.Â
Note: Whitespace inside the parent elements is considered as text, and text is considered as nodes.Â
Â
Example : To get the node name of the first child.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
}
#GFG {
font-size: 20px;
}
</style>
</head>
<body style="margin-left:140px;">
<h1>
GeeksForGeeks
</h1>
<h2>DOM firstChild Property </h2>
<div id="GFG">
<p>first Node</p>
<span> Second Node </span>
<p>ThirdNode</p>
</div>
<br/>
<!--Driver Code Ends-->
<button onclick="Geeks()">
Submit
</button>
<p id="sudo" style="font-size:25PX;"></p>
<script>
function Geeks() {
var x =
document.getElementById("GFG").firstElementChild.nodeName;
document.getElementById("sudo").innerHTML =
"node name of the first child node "
+ "of a <div> element:" + x;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- node.firstChild can be an Element, Text node, Comment node, or any other node type. It returns null if the node has no children.
- Browsers insert Text nodes for whitespace in the HTML source. As a result, element.firstChild frequently returns a #text node instead of the first element child. To get only the first element child, use element.firstElementChild instead.