Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

web

I am learning about DOM, and I can't understand: What is the difference between firstChild and firstElementChild?

like image 821
Phuc Ngo Avatar asked Jul 11 '18 08:07

Phuc Ngo


People also ask

What is firstElementChild in JS?

firstElementChild read-only property returns an element's first child Element , or null if there are no child elements. Element. firstElementChild includes only element nodes. To get all child nodes, including non-element nodes like text and comment nodes, use Node.

Which among the listed below is the property to access the first child of a node in Javascript?

Getting First Child Element of a Node In order to get the first child element of a node, it is required to use the firstChild property of the element. Syntax: let firstChild = parentElement.


1 Answers

The difference between this property and firstChild, is that firstChild returns the first child node as an element node, a text node or a comment node (depending on which one's first), while firstElementChild returns the first child node as an element node (ignores text and comment nodes).

for more info : HTML DOM firstElementChild

In the example below, you can see that firstChild returns the comment node and firstElementChild returns the element child i.e <li> A </li>

const ul = document.querySelector( 'ul' );

console.log( ul.firstElementChild );
console.log( ul.firstChild );
<ul><!--This is a comment node-->
        <li> A </li>
        <li> B </li>
        <li> C </li>
    </ul>
like image 109
jarvis Avatar answered Oct 20 '22 03:10

jarvis