What is the difference between `firstChild` and `firstElementChild`?

The difference boils down to the difference between a Node and an Element.
Every Element is also a Node, but a Node can also be a Text node, a Comment node, or something else.

firstElementChild returns the first child Element node, whereas firstChild returns the first child Node, regardless of whether it’s an Element, a Text, a Comment, or something else.

In the example below, you can see that firstChild returns the Comment node or Text node and firstElementChild always returns the Element child i.e. <li>A</li>.
Look into your browser console (F12) to see the results.

const example1 = document.querySelector("ul.example1"),
  example2 = document.querySelector("ul.example2");

console.log(example1.firstChild); // #text "\n  "
console.log(example1.firstElementChild); // <li>A</li>
console.log(example2.firstChild); // <!--  This is a comment node.  -->
console.log(example2.firstElementChild); // <li>X</li>
<ul class="example1">
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>
<ul class="example2"><!-- This is a comment node. -->
  <li>X</li>
  <li>Y</li>
  <li>Z</li>
</ul>

If you’re wondering why someElement.firstChild.appendChild or .innerHTML, or .addEventListener, etc. doesn’t work — either doesn’t do anything or throws a TypeError —, then someElement.firstChild most likely is a Text node, which, unlike an Element node, doesn’t have any of these properties.

Leave a Comment