What is the difference between firstChild and firstChildElement in Javascript?

I was trying to get the value of the first list item of an unordered list using “firstChild” attribute.

It threw error.

I tried the same using “firstElementChild” and it worked!

The difference it happens to be is:

“firstChild” considers text entered in between html tags as a child element too in addition to html tags

whereas

“firstElementChild” ignores text and comments between html tags and only considers html elements as a child.

For example:

Here is a list item :

<ul id="list">
<li>Item1</li>
<li>Item2</li>
</ul>

I printed the first child of the unordered list with id “list” using the below javascript code :


<script type="text/javascript">


  var list = document.getElementById("list");
  
  console.log("First child value is",list.firstChild);
  
  console.log("First element child value is",list.firstElementChild);

</script>

And here is what got printed in the console:

But wait there is nothing entered after the unordered list!

Or did I?

Yes I pressed enter after the <ul> tag which is considered as a text element.

Again if you expand $text printed above you can see it:

You can also enter comments after the <ul> tag which will be considered by “firstChild” attribute but not “firstElementChild” attribute.

For the below code :

<ul id="list"><!-- a list item -->
<li>Item1</li>
<li>Item2</li>
</ul>

The below script:

<script type="text/javascript">


  var list = document.getElementById("list");
  
  console.log("First child value is",list.firstChild);
  
  console.log("First element child value is",list.firstElementChild);

</script>

prints the below output:

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s