With the HTML DOM, you can navigate the node tree using node relationships. This allows you to find elements relative to each other (parents, children, and siblings) without knowing their specific IDs or classes.
The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships.
A common pitfall is that "Nodes" include whitespaces and comments. Modern developers often prefer Element-specific navigation to ignore non-element nodes.
| Generic Node (Includes Text) | HTML Element Node (Tags Only) |
|---|---|
parentNode |
parentElement |
childNodes |
children |
firstChild |
firstElementChild |
nextSibling |
nextElementSibling |
// Get the parent of an element
let myParent = document.getElementById("child").parentElement;
// Get the first child tag
let firstTag = document.getElementById("list").firstElementChild;
// Get the text of the next sibling
let nextText = element.nextElementSibling.innerHTML;
children and parentElement) unless you explicitly need to
handle raw text nodes or comments. It prevents unexpected errors caused by blank lines in
your HTML.
children to ignore text nodes and see only HTML tagsparentElement is the most common way to move "up" the tree