How to get the child and parent elements of a DOM element

Overview

We use the parentElement property of a Node object to get the parent element of a DOM element. Similarly, we utilize the children property of the Element object to get all the children of a DOM element as a live HTMLCollection.

Example

Console
Getting the parent and children of the DOM element

Explanation

  • Lines 5–10: We create a div element with the parent ID. Inside this element, we have another div element with a first_child ID. Inside the first_child div element, we add two span elements.
  • Line 13: We create a variable named firstChild and assign the div element with the first_child ID as a value.
  • Line 14: We access the parentElement property of the firstChild object.
  • Line 15: We print the HTML content of the parentElement using the outerHTML property.
  • Line 17: We access the children property of the firstChild object and store it in the variable named children.
  • Lines 18–20: We loop the children variable and print the HTML content of all child elements.