DOM traversal in JavaScript
Tags: webdev, javascript, programming, dom
Published: 2023-08-21 13:39:03

## Introduction

The Document Object Model (DOM) represents the structure of an HTML document. Navigating or "traversing" this structure is a fundamental aspect of web development, enabling developers to select, modify, delete, or add content on a webpage. This comprehensive guide delves deep into the art of DOM traversal using JavaScript, equipping you with a robust toolkit for handling various traversal scenarios.

We've done a more comprehensive version of this article over on [Accreditly's website](https://accreditly.io): [A guide to DOM traversal in JavaScript](https://accreditly.io/articles/a-guide-to-dom-traversal-in-javascript).

An remember, if you're interested in showcasing your JavaScript skills then be sure to check out our [JavaScript Fundamentals certification](https://accreditly.io/certifications/javascript-fundamentals).

## 1\. Basic DOM Selectors

Before we jump into traversal, let's review some fundamental DOM selectors.

-   getElementById(): Returns a reference to the first element with the specified ID.

```javascript
const header = document.getElementById('header');
```

-   getElementsByClassName(): Returns a live HTMLCollection of elements with the given class name.

```javascript
const buttons = document.getElementsByClassName('btn');
```

-   getElementsByTagName(): Returns a live HTMLCollection of elements with the given tag name.

```javascript
const paragraphs = document.getElementsByTagName('p');
```

-   querySelector(): Returns the first element that matches a specified CSS selector.

```javascript
const mainImage = document.querySelector('.main-image');
```

-   querySelectorAll(): Returns a static NodeList representing elements that match a specified CSS selector.

```javascript
const listItems = document.querySelectorAll('ul li');
```

## 2\. Parent, Child, and Sibling Relationships

At the core of DOM traversal are the relationships between nodes.

### 2.1. Parent Nodes

-   parentNode: Returns the parent node of a specified element.

```javascript
const parentOfButton = document.querySelector('.btn').parentNode;
```

### 2.2. Child Nodes

-   firstChild & lastChild: Return the first and last child of a node, respectively.

```javascript
const firstChildOfDiv = document.querySelector('div').firstChild;
const lastChildOfDiv = document.querySelector('div').lastChild;
```

-   children: Returns an HTMLCollection of an element's child elements (excludes text and comment nodes).

```javascript
const divChildren = document.querySelector('div').children;
```

-   firstElementChild & lastElementChild: Similar to `firstChild` and `lastChild`, but strictly return element nodes.

```javascript
const firstElementChildOfDiv = document.querySelector('div').firstElementChild;
```

### 2.3. Sibling Nodes

-   nextSibling & previousSibling: Return the next and previous sibling of an element, respectively.

```javascript
const nextToButton = document.querySelector('.btn').nextSibling;
const prevToButton = document.querySelector('.btn').previousSibling;
```

-   nextElementSibling & previousElementSibling: Similar to `nextSibling` and `previousSibling`, but strictly for element nodes.

```javascript
const nextElementToButton = document.querySelector('.btn').nextElementSibling;
```

## 3\. Traversal Methods

### 3.1. Node Iteration

-   childNodes: Returns a NodeList of child nodes.

```javascript
const listNodes = document.querySelector('ul').childNodes;
```

### 3.2. Filtering Elements

Utilize `Array.prototype.filter` to filter nodes based on conditions.

```javascript
const listItems = document.querySelector('ul').children;
const redItems = [...listItems].filter(item => item.style.color === 'red');
```

## 4\. DOM Traversal with Events

Combine event listeners with traversal methods to create interactive elements.

```javascript
document.querySelector('.btn').addEventListener('click', function(e) {
  const nextElement = e.target.nextElementSibling;
  if (nextElement) {
    nextElement.style.display = 'none';
  }
});
```

## 5\. Advanced Traversal Techniques

### 5.1. Recursive Traversal

Traverse the entire DOM tree recursively. This method is useful when the depth is unknown:

```javascript
function traverseDOM(node) {
  console.log(node);
  const children = node.children;
  for (let child of children) {
    traverseDOM(child);
  }
}

traverseDOM(document.body);
```

### 5.2. Climbing Up the DOM

In some cases, you may need to find a parent element with a specific selector:

```javascript
function findAncestor(el, selector) {
  while ((el = el.parentElement) && !el.matches(selector));
  return el;
}

const listItem = document.querySelector('li');
const containingDiv = findAncestor(listItem, 'div');
```

Mastering DOM traversal is paramount for any full-stack or frontend developer. JavaScript provides a plethora of methods and properties to navigate the intricate relationships of the DOM.