JavaScript – Get Last Child of an HTML Element

To get the last child of a specific HTML Element, using JavaScript, get reference to this HTML element, and read the lastElementChild property of this HTML Element.

lastElementChild property returns the last child of this HTML Element as Element object.

In the following example, we will get the last child of the HTML Element, which is selected by id "myElement", and change the font color of this last child to red.

example.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        #myElement{
            border: 1px solid green;
            display: inline-block;
            padding: 5px;
        }
    </style>
</head>
<body>
    <h2>Get Last Child of HTML Element using JavaScript</h2>
    <div id="myElement">
        <p>HTML Element Part 1.</p>
        <p>HTML Element Part 2.</p>
        <p>HTML Element Part 3.</p>
    </div>
    <br><br>
    <button type="button" onclick="execute()">Click Me</button>
    <script>
    function execute(){
        var element = document.getElementById('myElement');
        var lastChild = element.lastElementChild;
        lastChild.style.color = "red";
    }
    </script>
</body>
</html>

Try this html file online, and click on the Click Me button. The script gets the last child of the HTML Element #myElement, and changes its color to red.

JavaScript - Get Last Child of an HTML Element

Conclusion

In this JavaScript Tutorial, we learned how to get the last child of an HTML Element, using JavaScript.