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
Explanation
- Lines 5–10: We create a
divelement with theparentID. Inside this element, we have anotherdivelement with afirst_childID. Inside thefirst_childdivelement, we add two span elements. - Line 13: We create a variable named
firstChildand assign thedivelement with thefirst_childID as a value. - Line 14: We access the
parentElementproperty of thefirstChildobject. - Line 15: We print the HTML content of the
parentElementusing theouterHTMLproperty. - Line 17: We access the
childrenproperty of thefirstChildobject and store it in the variable namedchildren. - Lines 18–20: We loop the
childrenvariable and print the HTML content of all child elements.