The HTML DOM firstElementChild Property will return the first child of any node PreRequisites DOM (Document Object Model)
Parameters:Â No parameters are required.
Return value:Â The values returned by firstElementChild property are the following:Â
- A Node object: Representing the first child element of an element.
- Null: If there are no child elements.
SyntaxÂ
node.firstElementChild()Example: In this example, we will use HTML DOM firstElementChild Property.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM firstElementChild Property
</title>
</head>
<body>
<p>GeeksForGeeksTopics</p>
<ul id="Sections">
<li>Array</li>
<li>LinkedList</li>
<li>Stack</li>
<li>Queue</li>
<li>Tree</li>
<li>Graph</li>
</ul>
<p>
Click the button to get the first child
of the node having id is "Sections".
</p>
<!--button is used to run example function-->
<!--Driver Code Ends-->
<button onclick="example()">Click</button>
<p id="GeeksForGeeks sections first node"></p>
<script>
function example() {
let x = document.getElementById("Sections")
.firstElementChild.innerHTML;
document.getElementById("GeeksForGeeks sections" +
" first node").innerHTML = x;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Unlike firstChild (which can return a Text or Comment node), element.firstElementChild skips non-element nodes and returns only the first Element child, or null if none exist.
- Use firstElementChild when you want the first child element (ignoring whitespace text nodes and comments). Use firstChild when you need the first child of any node type. Related properties: lastElementChild, nextElementSibling, and previousElementSibling.