JavaScript – Get First Child of an HTML Element

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

firstElementChild property returns the first child of this HTML Element as Element object.

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

example.html

<!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 First 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 firstChild = element.firstElementChild;
        firstChild.style.color = "red";
    }
    </script>
</body>
</html>
Try Online

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

JavaScript - Get First Child of an HTML Element

Conclusion

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