About
This article shows you how to select the first child element.
Method
via the child selector
The best way to get the first child of a parent is through the child selector (>)
Example:
- A parent, a child and a grand child
<div class="parent">
<div>
<p>Grand Child</p>
</div>
<p>Child</p>
</div>
- The selection of the p child and setting its color
// select the first node within the first descendant node with the class parent
let firstChild = document.querySelector(".parent > p");
// set the color
firstChild.style.color="darkviolet";
- Output:
How to get the first child of a selected element
This example shows you how to get the child of already selected element (ie via a chained querySelect selection and the scope pseudo class)
Example:
- A parent and a child
<div class="parent">
<div>
<p>Grand Child</p>
</div>
<p>Child</p>
</div>
- The selection of the p child and setting its color
let firstChild = document
.querySelector(".parent") // select the first node with the class parent
.querySelector(":scope > p"); // select the first p of the actual selected element
firstChild.style.color="darkviolet";
- Output:
Be aware that if you just set the element name, you get actually, the first descendant and not the first child
let firstChild = document
.querySelector(".parent") // select the first node with the class parent
.querySelector("p"); // select the first p desendant
firstChild.style.color="darkviolet";
In the output: the grand child is selected, not the first child:
via the firstChild property
TLDR: Don't use it to select the first element
Why you should avoid this method ?
Because the firstChild property returns a any kind of node. It means that it may returns a text node and not an element node.
It means that if there is any character (such as end of line included) between the two tag element, the first child would be a text node.
That's why this method is not reliable.
Demo:
<div class="parent">
<p>Child</p>
</div>
let firstChild = document.querySelector(".parent").firstChild;
if(firstChild.nodeType === Node.TEXT_NODE){
console.log("The first node is a text node containing an end of line character");
}