JavaScript’s Node.lastChild read-only property returns the Node’s last child or null if the Node has no children.


A Node object or null if the node has no children.


Here is an example of using the lastChild property.

Consider the following lines of HTML:

<p id="paragraph">
 <span><b>JavaScript</b> is one of the most important programming languages.</span>

If we run the following lines of JavaScript, what do you think will be logged to the console?

let paragraph = document.getElementById('paragraph');

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 after 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 lastChild and lastElementChild?

The Node.lastChild property is very similar to the Element.lastElementChild property. Their only difference is that the latter ignores Comment and Text nodes and only returns Element nodes.

Browser compatibility

Internet Explorer
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
lastChild 1 12 1 6 12.1 1 18 45 12.1 1 1.0 4.4

See also