English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM firstChild Property

HTML DOM Element Object

firstChildA read-only property that returns the first child of a specified node as a Node object.

If the specified node has no child nodes, this method will returnEmptyValue.

Whitespace inside an element is considered text, and text is considered a node. Comments are also considered nodes.

To avoid the problem of firstChild returning #text or #comment nodes, you can usefirstElementChildIt only returns the first element node.

To return the last child of a specified node, uselastChildProperty.

Syntax:

node.firstChild
<div>
   <p>This is the first child inside the DIV:</p>1个P</p>
   <p>This is the first child inside the DIV:</p>2个P</p>
   <p>This is the first child inside the DIV:</p>3个P</p>
</div>
<script>
var x = document.querySelector("div").firstChild.nodeName;
document.getElementById("result").innerHTML = x;
</script>
Test and See‹/›

However, if we remove the space between the DIV and the first P element, the returned value will be a P tag instead of #text:

<div><p>This is the first paragraph inside a DIV tag.1个P</p>
   <p>This is the first child inside the DIV:</p>2个P</p>
   <p>This is the first child inside the DIV:</p>3个P</p>
</div>
<script>
var x = document.querySelector("div").firstChild.nodeName;
document.getElementById("result").innerHTML = x;
</script>
Test and See‹/›

Browser Compatibility

All browsers fully support the firstChild property:

Property
firstChildYesYesYesYesYes

Technical Details

Return Value:A Node object representing the first child of a node; if there are no child nodes, it isnull
DOM Version:DOM Level1

Related References

HTML DOM Reference:node .lastChild property

HTML DOM Reference:node .childNodes property

HTML DOM Reference:node .parentNode property

HTML DOM Reference:node .nextSibling property

HTML DOM Reference:node .previousSibling property

HTML DOM Reference:node .nodeName property

HTML DOM Element Object