top of page

JavaScript DOM Traversal

Updated: Jun 9, 2023

When working with JavaScript and the Document Object Model (DOM), there are various methods available to access and select DOM elements.


Here are some of the methods that we use to refer to DOM nodes.

  • getElementsByTagName()

  • getElementsByClassName()

  • getElementById()

  • querySelector()

  • querySelectorAll()

In this article, we will explore a different approach to DOM traversal that allows for a more connected way of accessing and manipulating DOM nodes. We will leverage the properties related to parent, child, and sibling relationships within the DOM tree.


To facilitate the explanation, we will create a sample project with an HTML file containing a few DOM nodes. The structure of the HTML file will resemble the following:

<!DOCTYPE html>
<html>
    <head>
        <!-- Head content -->
    </head>
    
    <body>
        <!-- DOM nodes -->
    </body>
</html>

Throughout the article, we will utilize parent, child, and sibling properties to traverse the DOM and interact with different elements within the structure.


By understanding these DOM traversal techniques, you will gain the ability to efficiently navigate the DOM tree, select specific elements, and perform operations on them dynamically. This approach offers a more flexible and comprehensive way to interact with the DOM and build robust web applications.

Code:

<!DOCTYPE html>
<html>
    <head>
    <title> DOM Traversal</title>
    
    <style>
        *{ border: 3px solid Blue; padding: 15px; margin: 15px;}
        html { margin:0; padding:0;}
        body {max-width:600px; font-family:sans-serif; color: Black;}
    </style>
    </head>
    
    <body>
    <h1>Favourite Movies</h1>
    <p>The world's leading movies <strong>all</strong> in one place</p>
    <h2>The 5 Movies are:</h2>
    <ul>
        <li>Harry Potter</li>
        <li>Spider Man</li>
        <li>Intersteller</li>
        <li>Fast and Furious </li>
        <li>Peter Pan</li>
    </ul>
    </body>
    
    <script>
        const h1Element = document.hetElementsByTagName('h1')[0];
        const pElement = document.hetElementsByTagName('p')[0];
        const ulElement = document.hetElementsByTagName('ul')[0];
    </script>
</html>  

When running the provided code in a browser, the output would appear as follows:


In the above code, document.querySelector is used to select elements from the DOM based on CSS selector syntax. Here, we select the <h1>, <p>, and <ul> elements.


Once these variables are set up, we can perform DOM traversal operations and manipulate the selected elements according to our requirements.


Now that we have established the variable setup, we can proceed with exploring DOM traversal and understanding how to navigate the DOM tree and interact with its nodes.


By utilizing these variables and applying DOM traversal techniques, we can dynamically interact with specific elements, modify their properties, and create powerful and interactive web applications.


Root Node

At the very top of the DOM tree lies the root node. This node represents the entire document and is often referred to as the document node. In JavaScript, the root node is accessed through the document object, which is a property of the window object. Even when a blank HTML document is loaded, it contains a root node and root elements.


Now let’s explore the rest of the nodes.

The nodes in the DOM tree are referred to as parents, children, and siblings based on their relationships. This is no different than a real-world family tree. Hence this concept will be more familiar and relatable to you.

Parents Nodes

A parent node is a node that is directly above another node in the DOM tree. It is closer to the document in the hierarchy. For instance, in our example, the <html> tag is the parent node of the <head>, <body>, and <script> tags. Similarly, the <body> tag is the parent of <h1>, <h2>, <p>, and <ul>. However, <li> is not the child of <body> because it is two levels down from the body. To access the parent of a node, we can use the parentNode property or the parentElement property.

To traverse to the parent of a node, the following DOM traversal method can be used:

<currentNode>.parentNode;

Apart from using parentNode, the parentElement property can also be used to retrieve the parent element node. This provides an alternative way to access the parent node of a given element in the DOM tree.


Let's consider an example where we need to retrieve the grandparent of the current node, which is two levels above. We can use the same mechanism of parentNode multiple times to traverse up the DOM tree.


To retrieve the grandparent of a node, we can use the following code:

currentNode.parentNode.parentNode;

By calling parentNode twice, we can access the grandparent of the current node. For instance, if we apply this to the <p> element, it will return the <html> element.


It's important to note that the parent element of the <html> element is the document itself. Therefore, if you attempt to retrieve the parent element of <html>, it will return null. However, the parent node of <html> will be represented as #document.


This distinction between parentElement and parentNode is vital to understand when working with different elements in the DOM. Depending on your specific needs, you can choose the appropriate property to access the desired parent node or parent element.


Children Nodes

Nodes that are one level below the current node are considered its children nodes. They are the direct descendants of the current node. To access child nodes, there are several properties that can be used.


In our example, the list has 11 children. It's important to note that in manually generated HTML, white spaces (indentation) are considered separate child nodes. Thus, the number of child nodes may include text nodes representing indentation. To modify the properties or styles of child nodes, we can use DOM traversal techniques.


Now, let's explore how to modify styles using the DOM traversal mechanism. In this example, we will demonstrate how to change the background color of the first child of a list using JavaScript.


To begin, we assume we have a variable named list that represents the list element. Here's how we can accomplish this:

list.firstElementChild.style.background = 'yellow';

In the above code snippet, we use the firstElementChild property instead of firstChild to retrieve the first child node of the list. The reason for using firstElementChild is that firstChild may return a text node due to indentation or whitespace. However, to target the first <li> element specifically, we need to use firstElementChild.


By accessing the style property of the first child node, we can modify various CSS properties. In this case, we set the background property to 'yellow', effectively changing the background color of the first list item.


It's worth noting that this approach can be used to modify any other CSS property, not just the background color. You can change properties such as color, font-size, border, and many more.


By understanding the distinction between firstChild and firstElementChild, you can accurately target specific elements within the DOM tree and apply desired styles.


Remember to ensure that the DOM has loaded before attempting to access and modify elements. You can achieve this by wrapping your JavaScript code in an event listener for the DOMContentLoaded event or by placing the script at the end of the HTML document, just before the closing </body> tag.


Sibling Nodes

Sibling nodes are nodes that are at the same level in the DOM tree, sharing the same parent. They can be of the same type or different types of elements. Understanding sibling nodes is crucial for fully traversing the DOM tree.


Sibling properties allow us to access sibling nodes and manipulate their properties. For example, we can use the previousSibling and nextSibling properties to navigate to the previous and next sibling nodes, respectively. These properties can be chained together to traverse the DOM tree.

Similar to parent and child node elements, sibling properties can be chained together as well.

Conclusion

DOM traversal is very fascinating if you know the correct and efficient way to do it. In this article we explored one way of traversing the DOM, mainly using parent, child, and sibling nodes. Now that you know this concept, the possibilities are endless.

0 comments

Recent Posts

See All

Commentaires


bottom of page