Traveling Through Nodes
Every HTML element on a web page is connected to others. They have neighbors, parents, and children, forming what we call the " DOM Tree " . By understanding these relationships, you can write JavaScript that easily moves from one element to another to find exactly what it needs.
Types of Nodes
Before we navigate, it's crucial to understand that everything in the DOM is a " node " , but not all nodes are HTML tags.
- Element Nodes: These are the actual HTML tags like
<div>,<span>,<p>, or<body>. This is usually what you want to work with. - Text Nodes: The pure text written inside the tags. Even a line break or empty space in your HTML file creates a text node!
- Comment Nodes: Hidden HTML comments.
How to Navigate
The DOM provides specific properties to travel up, down, and sideways across the tree:
- Upwards: Use
parentElementto find the tag that directly contains your current element. - Downwards: Use
childrento get a list of all child elements (tags only) inside the current element. - Sideways: Use
nextElementSiblingorpreviousElementSiblingto find elements that are on the same level (siblings).
Let's try finding the parent element of the body tag! Type the command below and hit Run:
Type: document.body.parentElement.tagName
Now let's see how many direct child elements the <head> tag has:
Type: document.head.children.length
Pro Tip: Always prefer properties with the word " Element " in them (like children, firstElementChild, nextElementSibling). If you use older properties like childNodes or firstChild, your code will often accidentally grab empty text nodes or line breaks instead of the actual HTML tags you wanted!