DEV Community

Cover image for DOM traversal in JavaScript
Accreditly
Accreditly

Posted on

DOM traversal in JavaScript

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: 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.

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.
const header = document.getElementById('header');
Enter fullscreen mode Exit fullscreen mode
  • getElementsByClassName(): Returns a live HTMLCollection of elements with the given class name.
const buttons = document.getElementsByClassName('btn');
Enter fullscreen mode Exit fullscreen mode
  • getElementsByTagName(): Returns a live HTMLCollection of elements with the given tag name.
const paragraphs = document.getElementsByTagName('p');
Enter fullscreen mode Exit fullscreen mode
  • querySelector(): Returns the first element that matches a specified CSS selector.
const mainImage = document.querySelector('.main-image');
Enter fullscreen mode Exit fullscreen mode
  • querySelectorAll(): Returns a static NodeList representing elements that match a specified CSS selector.
const listItems = document.querySelectorAll('ul li');
Enter fullscreen mode Exit fullscreen mode

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.
const parentOfButton = document.querySelector('.btn').parentNode;
Enter fullscreen mode Exit fullscreen mode

2.2. Child Nodes

  • firstChild & lastChild: Return the first and last child of a node, respectively.
const firstChildOfDiv = document.querySelector('div').firstChild;
const lastChildOfDiv = document.querySelector('div').lastChild;
Enter fullscreen mode Exit fullscreen mode
  • children: Returns an HTMLCollection of an element's child elements (excludes text and comment nodes).
const divChildren = document.querySelector('div').children;
Enter fullscreen mode Exit fullscreen mode
  • firstElementChild & lastElementChild: Similar to firstChild and lastChild, but strictly return element nodes.
const firstElementChildOfDiv = document.querySelector('div').firstElementChild;
Enter fullscreen mode Exit fullscreen mode

2.3. Sibling Nodes

  • nextSibling & previousSibling: Return the next and previous sibling of an element, respectively.
const nextToButton = document.querySelector('.btn').nextSibling;
const prevToButton = document.querySelector('.btn').previousSibling;
Enter fullscreen mode Exit fullscreen mode
  • nextElementSibling & previousElementSibling: Similar to nextSibling and previousSibling, but strictly for element nodes.
const nextElementToButton = document.querySelector('.btn').nextElementSibling;
Enter fullscreen mode Exit fullscreen mode

3. Traversal Methods

3.1. Node Iteration

  • childNodes: Returns a NodeList of child nodes.
const listNodes = document.querySelector('ul').childNodes;
Enter fullscreen mode Exit fullscreen mode

3.2. Filtering Elements

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

const listItems = document.querySelector('ul').children;
const redItems = [...listItems].filter(item => item.style.color === 'red');
Enter fullscreen mode Exit fullscreen mode

4. DOM Traversal with Events

Combine event listeners with traversal methods to create interactive elements.

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

5. Advanced Traversal Techniques

5.1. Recursive Traversal

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

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

traverseDOM(document.body);
Enter fullscreen mode Exit fullscreen mode

5.2. Climbing Up the DOM

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

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

const listItem = document.querySelector('li');
const containingDiv = findAncestor(listItem, 'div');
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
artydev profile image
artydev

Thank you 🙂

Collapse
 
xuanchinh97 profile image
Trịnh Xuân Chinh

Useful. Thanks so much