The core difference between the firstChild and firstElementChild DOM element properties is that,
-
The
firstChildDOM element property returns atext,comment, or anElementas the value. Put simply, it returns the first thing that comes as the first child of an element. -
The
firstElementChildelement property on the other hand returns the firstElementas the value. Even If there aretextorcommentwhich comes before it, it doesn't return thetextor thecommentas the values.
Let's look at an example.
Consider this div tag with some text and a span tag inside it as its children.
<div>
Hello World!
<span>I'm inside a SPAN tag</span>
</div>
Now let's use the firstChild and the firstElementChild DOM element properties on the div element to check what it returns.
// get reference to the div tag
const div = document.querySelector("div");
// firstChild DOM element property
const firstChild = div.firstChild;
// firstElementChild DOM element property
const firstElementChild = div.firstElementChild;
console.log(firstChild); // Hello World!
console.log(firstElementChild); // <span>I'm inside a SPAN tag</span>
As you can see the firstChild returns the text content Hello World! and the firstElementChild returns the span tag <span>I'm inside a SPAN tag</span>.
See this example live in JSBin.