DOM traversing describes how to navigate the tree-like structure that HTML documents generate. Here’s a complete guide on how to traverse the DOM with JavaScript.
What Is DOM Traversing?
The Document Object Model, or DOM for short, is a tree-like representation of an HTML document. It provides an API that allows you, as the web developer, to interact with a website using JavaScript.
Every item in the DOM is known as a node. Only through the DOM can you manipulate your HTML document structure, content, and style.
DOM traversal (also called walking or navigating the DOM) is the act of selecting nodes in the DOM tree from other nodes. You’re probably already familiar with several methods for accessing elements in the DOM tree by their id, class, or tag name. You can use methods like document.querySelector() and document.getElementById() to do so.
There are other methods you can use in conjunction, to navigate the DOM in more efficient and robust ways. As you can imagine, it’s better to search from an already-known point on a map than do a full search.
For example, selecting a child element from its parent is easier and more efficient than searching for it throughout the entire tree.
A Sample Document to Traverse
Once you have access to a given node in the DOM tree, you can access its related nodes in different ways. You can move downwards, upwards, or sideways in the DOM tree from your selected node.
The first method involves searching for an element starting with a top-most node (like the document node) and moving downwards.
The second way is the opposite: you move from an inner element up the tree, searching for an outer element. The last method is when you search for an element from another element at the same level (meaning the two elements are siblings) in the document tree.
To demonstrate, consider this example HTML document:
Traversing the DOM Downwards
You can traverse the DOM downwards using one of two methods. The first one is the common selector method (element.querySelector or element.querySelectorAll). Secondly, you can use the children or childNodes property. There are also two other special properties, namely, lastChild and firstChild.
Using Selector Methods
The querySelector() methods allow you to search for one or more elements that match a given selector. For example, you can search for the first element with a class of “first-article” using document.querySelector(’.first-article’). And to fetch all h2 elements in the document, you can use the querySelectorAll method: document.querySelectorAll(‘h2’). The querySelectorAll method returns a node list of matching elements; you can select each item using bracket notation:
The major catch when using selector methods is you must use the appropriate symbols, where applicable, before the selector as you do in CSS. For example, “.classname” for classes and “#id” for ids.
Remember the result will be an HTML element, not just the inner content of the selected element. To access the content you can use the node’s innerHTML property:
Using the children or childNodes Properties
The children property selects all child elements that are directly under a given element. Here’s an example of the children property in action:
Logging apples to the console will display a set of all list items directly under the element with an “apple-list” class as an HTML collection. An HTML collection is an array-like object, so you can use bracket notation to select items, as with querySelectorAll.
Unlike the children property, childNodes returns all direct child nodes (not just child elements). If you are only interested in child elements, say list items only, use the children property.
Using Special lastChild and firstChild Properties
These two methods are not as robust as the first two. As their names suggest, the lastChild and firstChild properties return an element’s last and first child nodes.
Traversing the DOM Upwards
You can navigate up the DOM using the parentElement (or parentNode) and closest properties.
Using parentElement or parentNode
Both parentElement or parentNode properties let you select the selected element’s parent node one level up. The critical difference is that parentElement only chooses the parent node that is an element. On the other hand, parentNode can select a parent regardless of whether it’s an element or a different node type.
In the code sample below, we use parentElement to select the div with the “wrapper-1” class from “apple-list”:
Using the closest Property
The closest property selects the first parent element that matches a specified selector. It lets you select multiple levels up instead of one. For instance, if we already have the button with class “btn-1” selected, we can select the main element using the closest property as follows:
Like querySelector and querySelectorAll, use appropriate selectors in the closest method.
Traversing the DOM Sideways
There are two methods available for walking the DOM sideways. You can use nextElementSibling or previousElementSibling. Use nextElementSibling to select the following sibling element and previousElementSibling to select the previous sibling.
There are also equivalent nextSibling and previousSibling properties that also select from all node types, not just elements.
Do More by Chaining DOM Traversal Properties and Methods
All the methods and properties above can enable you to select any node in the DOM. However, in some cases, you might want to move up first, then down or sideways. In that case, chaining different properties together will prove handy.