24

What is the difference between firstChild and firstElementChild?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Phuc Ngo
  • 241
  • 2
  • 3
  • 1
    https://stackoverflow.com/a/41196036 explains the differences between `firstElementChild` and `firstChild` – Adrian W Jul 11 '18 at 08:32

2 Answers2

25

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
jarvis
  • 251
  • 3
  • 5
2

You should use firstElementChild if your code is prettified.

This example demonstrates the use of firstChild and how whitespace nodes might interfere with using this property.

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • _“if your code is prettified”_ — That’s very unclear and very misleading. You should use `firstElementChild` if you expect to receive an Element, not depending on some unrelated external circumstances such as formatting. There is no such thing as “whitespace nodes”; those are Text nodes. They also don’t “interfere” with this property: the entire _purpose_ of `firstChild` is to potentially find Text nodes. – Sebastian Simon Jan 09 '23 at 14:24
  • @SebastianSimon Please make a PR to the [docs](https://developer.mozilla.org/en-US/docs/Web/API/Node/firstChild#Example:%7E:text=Example,-This:~:text=firstChild%20and%20how-,whitespace%20nodes,-might%20interfere%20with) too – Smart Manoj Jan 12 '23 at 11:21