DEV Community

Cover image for Differences between firstChild and firstElementChild DOM element property in JavaScript
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

Differences between firstChild and firstElementChild DOM element property in JavaScript

Originally posted here!

The core difference between the firstChild and firstElementChild DOM element properties is that,

  • The firstChild DOM element property returns a text, comment, or an Element as the value. Put simply, it returns the first thing that comes as the first child of an element.

  • The firstElementChild element property on the other hand returns the first Element as the value. Even If there are text or comment which comes before it, it doesn't return the text or the comment as 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

Feel free to share if you found this useful 😃.


Top comments (0)