How to Traverse the DOM Using JavaScript
Understanding the DOM is essential in your web development career. You should know how to select different elements in the DOM, so you can then read their contents or modify them.
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?
TheDocument Object Model, or DOM for short, is a tree-like representation of an HTML document. It provides anAPIthat 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 foraccessing elements in the DOM treeby their id, class, or tag name. You can use methods likedocument.querySelector()anddocument.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, it’s possible to 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.querySelectororelement.querySelectorAll). Secondly, you can use thechildrenorchildNodesproperty. There are also two other special properties, namely,lastChildandfirstChild.
Using Selector Methods
The querySelector() methods allow you to search for one or more elements that match a given selector. For example, you’re able to search for the first element with a class of “first-article” usingdocument.querySelector('.first-article'). And to fetch allh2elements in the document, you can use thequerySelectorAllmethod:document.querySelectorAll(‘h2’). ThequerySelectorAllmethod 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’re able to use the node’sinnerHTMLproperty:
Using the children or childNodes Properties
Thechildrenproperty selects all child elements that are directly under a given element. Here’s an example of thechildrenproperty in action:
Loggingapplesto 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 it’s possible to use bracket notation to select items, as with querySelectorAll.
Unlike thechildrenproperty,childNodesreturns all direct child nodes (not just child elements). If you are only interested in child elements, say list items only, use thechildrenproperty.
Using Special lastChild and firstChild Properties
These two methods are not as robust as the first two. As their names suggest, thelastChildandfirstChildproperties return an element’s last and first child nodes.
Traversing the DOM Upwards
you’re able to navigate up the DOM using theparentElement(orparentNode) andclosestproperties.
Using parentElement or parentNode
BothparentElementorparentNodeproperties let you select the selected element’s parent node one level up. The critical difference is thatparentElementonly chooses the parent node that is an element. On the other hand,parentNodecan select a parent regardless of whether it’s an element or a different node type.
In the code sample below, we useparentElementto select the div with the “wrapper-1” class from “apple-list”:
Using the closest Property
Theclosestproperty 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 themainelement using theclosestproperty as follows:
LikequerySelectorandquerySelectorAll, use appropriate selectors in theclosestmethod.
Traversing the DOM Sideways
There are two methods available for walking the DOM sideways. You can usenextElementSiblingorpreviousElementSibling. UsenextElementSiblingto select the following sibling element andpreviousElementSiblingto select the previous sibling.
There are also equivalentnextSiblingandpreviousSiblingproperties 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.
Event-handling is vital for interactive applications. Learn how to respond to mouse and keyboard events using JavaScript.
Don’t let aging hardware force you into buying expensive upgrades.
Anyone with more than a passing interest in motorsports must see these films.
Who asked for these upgrades?
Every squeak is your PC’s way of crying for help.
Unlock a world of entertainment possibilities with this clever TV hack.