I am learning about DOM, and I can't understand: What is the difference between firstChild
and firstElementChild
?
firstElementChild read-only property returns an element's first child Element , or null if there are no child elements. Element. firstElementChild includes only element nodes. To get all child nodes, including non-element nodes like text and comment nodes, use Node.
Getting First Child Element of a Node In order to get the first child element of a node, it is required to use the firstChild property of the element. Syntax: let firstChild = parentElement.
The difference between this property and firstChild, is that firstChild returns the first child node as an element node, a text node or a comment node (depending on which one's first), while firstElementChild returns the first child node as an element node (ignores text and comment nodes).
for more info : HTML DOM firstElementChild
In the example below, you can see that firstChild
returns the comment node and firstElementChild
returns the element child i.e <li> A </li>
const ul = document.querySelector( 'ul' );
console.log( ul.firstElementChild );
console.log( ul.firstChild );
<ul><!--This is a comment node-->
<li> A </li>
<li> B </li>
<li> C </li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With