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

HTML DOM lastChild Property

HTML DOM Element Object

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

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

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

To avoid the problem of lastChild returning #text or #comment nodes, you can uselastElementChildIt only returns the last element node.

To return the first child node of a specified node, usefirstChildProperties.

Syntax:

node.lastChild
<div>
   <p>This is the1a P</p>
   <p>This is the2a P</p>
   <p>This is the3a P</p>
</div>
<script>
var x = document.querySelector("div").lastChild.nodeName;
document.getElementById("result").innerHTML = x;
</script>
Test to see‹/›

However, if we remove the space after the last P element, the return value will be the P tag instead of #text:

<div>
   <p>This is the1a P</p>
   <p>This is the2a P</p>
   <p>This is the3a P</p></div>
<script>
var x = document.querySelector("div").lastChild.nodeName;
document.getElementById("result").innerHTML = x;
</script>
Test to see‹/›

Browser Compatibility

All browsers fully support the lastChild property:

Property
lastChildYesYesYesYesYes

Technical Details

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

Related References

HTML DOM Reference:node .firstChild 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