HTML DOM lastChild Property

Last Updated : 19 Aug, 2026

The DOM lastChild property is used to return the last child of the specified node. It returns the last child nodes as text, comment, or element nodes (depend on which occurs at last). It is a read-only property. 

Syntax

node.lastChild

Return Value: It returns a node object which represents the last child of the node and null if there are no child elements. 

Example 1: In this example, we will see the use of the DOM lastChild property

HTML
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
    <title>
        DOM lastChild Property
    </title>
</head>
<body style="text-align: center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h2>
        DOM lastChild Property
    </h2>
    <div id="div">
        <span>GeeksforGeeks! </span>
        <span>
            A computer science portal for geeks.
        </span>
    </div>
    <br>
<!--Driver Code Ends-->

    <button onclick="geek()">Click me!</button>
    <p id="p"></p>
    <script>
        function geek() {
            let doc =
                document.getElementById("div").lastChild.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-->

Example 2: In this example, we will see the use of the DOM lastChild property

html
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM lastChild Property
    </title>
</head>
<body style="text-align: center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h2>
        DOM lastChild Property
    </h2>
    <select id="sel" size="3">
        <option>Merge sort</option>
        <option>Quick sort</option>
        <option>Insertion sort</option>
    </select>
    <br><br>
<!--Driver Code Ends-->

    <button onclick="Geeks()">
        Click Here!
    </button>
    <p id="p"></p>
    <script>
        function Geeks() {
            let x =
                document.getElementById("sel").lastChild.text;
                document.getElementById("p").innerHTML
                    = "Last child: " + x;
        }
    </script>

<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
  • node.lastChild can be an Element, Text node, Comment node, or any other node type. It returns null if the node has no children.
  • Browsers insert Text nodes for trailing whitespace in the HTML source. As a result, element.lastChild frequently returns a #text node instead of the last element child. To get only the last element child, use element.lastElementChild instead.
Comment