HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Navigation

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.


Node Relationships

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.

  • parentNode: the elder node of the current node.
  • childNodes[n]: the list of child nodes.
  • firstChild / lastChild: the first and last child nodes.
  • nextSibling / previousSibling: the nodes on the same level.

Element vs. Node Navigation

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

Navigating Examples

// 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;
Best Practice: Always use the Element-specific versions (like 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.

Key Points to Remember

  • The DOM is a family tree of nodes
  • Nodes consist of Parents, Children, and Siblings
  • Text nodes (whitespaces) are often hidden "gotchas" in raw node navigation
  • Use children to ignore text nodes and see only HTML tags
  • parentElement is the most common way to move "up" the tree
  • Navigation is perfect for event delegation patterns