JavaScript’s Element.firstElementChild
read-only property returns the Element
’s first child element or null
if the Element
has no child elements.
Value
An Element
object or null
if the element has no child elements.
Examples
Here is an example of using the firstElementChild
property.
Consider the following lines of HTML:
<p id="paragraph">
<span>I like learning <b>JavaScript</b> programming.</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.firstElementChild.nodeName);
The correct answer is “SPAN.” That is because the span
element is the first – and last – child element of the p
element, and we selected the p
element by its id
and logged the name of its first child element to the console.
What is the difference between firstElementChild and firstChild?
The Element.firstElementChild
property is very similar to the Node.firstChild
property. Their only difference is that the former 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)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
firstElementChild |
1 | 12 | 3.5 | 9 | 10 | 4 | 18 | 4 | 10.1 | 3 | 1.0 | 37 |