JavaScript’s Node.firstChild
read-only property returns the Node
’s first child or null
if the Node
has no children.
Value
A Node
object or null
if the node has no children.
Examples
Here is an example of using the firstChild
property.
Consider the following lines of HTML:
<p id="paragraph">
<span><b>JavaScript</b> is one of the most important programming languages.</span>
</p>
If we run the following lines of JavaScript, what do you think will be logged to the console?
let paragraph = document.getElementById('paragraph');
console.log(paragraph.firstChild.nodeName);
You may have thought that the logged string would have been “span,” or something similar. So, why was “#text” logged to the console instead?
It was because there is some whitespace before the span
element, and any whitespace, from a single space to multiple spaces, will create a Text
node.
What if we modified our HTML like this and run the JavaScript again?
<p id="paragraph"><span><b>JavaScript</b> is one of the most important programming languages.</span></p>
Well, as expected, the logged string would be “SPAN.”
What is the difference between firstChild and firstElementChild?
The Node.firstChild
property is very similar to the Element.firstElementChild
property. Their only difference is that the latter ignores Comment
and Text
nodes and only returns Element
nodes.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
firstChild |
1 | 12 | 1 | 6 | 12.1 | 1 | 18 | 4 | 12.1 | 1 | 1.0 | 4.4 |