firstElementChild in javascript

firstElementChild property in javascript

firstElementChild property is used to return the first child of an element.

If there is no child element it returns null.

Syntax

var elem = element.firstElementChild;

Example - Getting the first child element

Try Yourself

Example Explanation

  • In the above example we have created a div (idDiv), it is the parent element.
  • Within the parent element, we have added two child elements (div, p).

  • When the button is clicked, fun_name() function is called.
  • In the Javascript function, first we are getting the parent element (document.getElementById("idDiv")) and storing it in attr variable.
  • Using the firstElementChild property, we are getting the first child element and displaying it (alert (attr.firstElementChild)).