The HTML DOM firstElementChild property is used for returning the first child element of a given element. The child element is returned as an element node only. It ignores the text and comment nodes and doesn’t consider them. This is a read-only property.
Syntax
Following is the syntax for HTML DOM firstElementChild property −
element.firstElementChild
Example
Let us look at an example for the firstElementChild property −
<!DOCTYPE html> <html> <head> <script> function eleChild() { var ch = document.getElementById("DIV1").firstElementChild.innerHTML; document.getElementById("Sample").innerHTML = "The first element child node of the div is :"+ch; } </script> </body> </html> <h1>firstElementChild property</h1> <div id="DIV1"> <p>This is a p element</p> <span>This is a span element</span> </div> <button onclick="eleChild()">Get Child</button> <p id="Sample"></p> </body> </html>
Output
This will produce the following output −
On clicking the “Get Child” method −
In the above example −
We have created a button “Get Child” that will execute the eleChild() method on being clicked by the user −
<button onclick="eleChild()">Get Child</button>
The eleChild() function gets the firstElementChild of the div with id “DIV1” and assign its innerHTML property to variable ch. Since firstElementChild doesn’t consider whitespace , it will return the <p> element. Using the innerHTML property we get the text inside the <p> element and display it in the paragraph with id “Sample” −
function eleChild() { var ch = document.getElementById("DIV1").firstElementChild.innerHTML; document.getElementById("Sample").innerHTML = "The first element child node of the div is :"+ch; }