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

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
ADVERTISEMENT

Conclusion

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