In this section, we will learn what the Element lastChild property is and how to use it in JavaScript.
What is Element lastChild Property in JavaScript?
The JavaScript Element lastChild property is used to get the last child of an element and return a reference of that child-element as a result.
Note: using this property will return the last child no-matter if it’s an Element-Node, Text-Node or a Comment-Node. But there’s another property called lastChildElement which will return the last child of an element that is of type Element-Node! That means for the lastChildElement property, if the last child of an element is in fact of type Text-Node for example, that will be ignored and instead this property will look for the last child of an element that is of type Element-Node.
JavaScript lastChild Property Syntax:
element.lastChild;
JavaScript lastChild Property Input Value
This property is read-only and so we can’t assign a new value to it.
JavaScript lastChild Property Return Value
The return value of this property is a reference to the last child of an element.
Note: If the target element does not have a child, then the return value of the property will be the value null.
Example: using lastChild Property in JavaScript
See the Pen using lastChild Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How Does Element lastChild property Work in JavaScript?
Here if you click on the button of the page, the result will be a node of type text! But how? Isn’t it the last element of this list the <li> item?
Well, not exactly! If you look carefully, the last <li> item is set on a line above the <ol> element. That means we have a newline character which is a text-node right between the last <li> element and the <ol> element! So technically, the last child of the <ol> is this newline character (which is of type text-node).
For this reason, calling the lastChild property gives us this text-node (the newline character) instead of the last <li> element.
Note: you could remove the newline between the last <li> and the closing </ol> elements which in that case, this last <li> item becomes the last child of the <ol>.
Example: element lastChild property in JavaScript:
See the Pen element lastChild property in JavaScript by Omid Dehghan (@odchan1) on CodePen.