The lastElementChild property returns the last child element of a specified element, or null if none exists. Unlike lastChild (which includes text and comment nodes), it returns only element nodes and is read-only.
Syntax
element.lastElementChildReturn Value: It returns an object which represents the last child of an element. If there is no child element then it returns null.Â
Example: In this article, we will use DOM lastElementChild property
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
DOM lastElementChild Property
</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
DOM lastElementChild Property
</h2>
<div id="GFG">
<span>GeeksforGeeks!</span>
<span>A computer science portal for geeks.</span>
</div>
<br>
<!--Driver Code Ends-->
<button onclick="Geeks()">
Click me!
</button>
<p id="p"></p>
<script>
function Geeks() {
let doc =
document.getElementById("GFG").lastElementChild.innerHTML;
document.getElementById("p").innerHTML = doc;
document.getElementById("p").style.color = "white";
document.getElementById("p").style.background = "green";
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Unlike lastChild (which can return a Text or Comment node), element.lastElementChild skips non-element nodes and returns only the last Element child, or null if none exist.
- Use lastElementChild when you want the last child element (ignoring trailing whitespace text nodes and comments). Use lastChild when you need the last child of any node type. Related properties: firstElementChild, nextElementSibling, and previousElementSibling.