Understanding the DOM is essential in your web development career.

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.

it’s possible for you to use methods likedocument.querySelector()anddocument.getElementById()to do so.

you could move downwards, upwards, or sideways in the DOM tree from your selected node.

The first one is the common selector method (element.querySelectororelement.querySelectorAll).

Secondly, it’s possible for you to use thechildrenorchildNodesproperty.

There are also two other special properties, namely,lastChildandfirstChild.

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.

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 could navigate up the DOM using theparentElement(orparentNode) andclosestproperties.

Using parentElement or parentNode

BothparentElementorparentNodeproperties let you snag the selected element’s parent node one level up.

The critical difference is thatparentElementonly chooses the parent node that is an element.

It lets you select multiple levels up instead of one.

Traversing the DOM Sideways

There are two methods available for walking the DOM sideways.

UsenextElementSiblingto opt for following sibling element andpreviousElementSiblingto opt for previous sibling.

There are also equivalentnextSiblingandpreviousSiblingproperties that also select from all node types, not just elements.

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.