If you want to access the last child of an HTML element, then JavaScript offers you two methods, lastChild
and lastElementChild
.
The lastChild
property returns the last child node of an element. The child node returned by the lastChild
property can be a text node, an element node, or a comment node.
The lastElementChild
property only returns the child node, which is the element node. It does not return text and comment nodes.
HTML Code
<!DOCTYPE html> <html> <head> <title>How to get the last child of an element in JavaScript</title> </head> <body> <p id="main">This text has a <b>bold</b> style.</p> <script src="app.js"></script> </body> </html>
JavaScript Code: app.js
let element = document.getElementById('main'); let lastChild = element.lastChild; console.log(lastChild.nodeName); console.log(lastChild.textContent); let lastElement = element.lastElementChild; console.log(lastElement.nodeName); console.log(lastElement.textContent);
Output
#text style. B bold
The DOM tree representation of the paragraph element is shown in the following image that clarifies which element is the last child node and the last child element.
In this code, you can see that the lastChild
property has returned the text node. On the other hand, the lastElementChild
property has returned the element node.