Introduction

The previous tutorial in this series, How to Access Elements in the DOM, covers how to use the built-in methods of the document object to access HTML elements by ID, class, tag name, and query selectors. We know that the DOM is structured as a tree of nodes with the document node at the root and every other node (including elements, comments, and text nodes) as the various branches.

Often, you will want to move through the DOM without specifying each and every element beforehand. Learning how to navigate up and down the DOM tree and move from branch to branch is essential to understanding how to work with JavaScript and HTML.

In this tutorial, we will go over how to traverse the DOM (also known as walking or navigating the DOM) with parent, child, and sibling properties.

Setup

To begin, we will create a new file called nodes.html comprised of the following code.

<!DOCTYPE html>
<html>
  <head>
    <title>Learning About Nodes</title>

    <style>
      * {
        border: 2px solid #dedede;
        padding: 15px;
        margin: 15px;
      }
      html {
        margin: 0;
        padding: 0;
      }
      body {
        max-width: 600px;
        font-family: sans-serif;
        color: #333;
      }
    </style>
  </head>

  <body>
    <h1>Shark World</h1>
    <p>
      The world's leading source on <strong>shark</strong> related information.
    </p>
    <h2>Types of Sharks</h2>
    <ul>
      <li>Hammerhead</li>
      <li>Tiger</li>
      <li>Great White</li>
    </ul>
  </body>

  <script>
    const h1 = document.getElementsByTagName('h1')[0]
    const p = document.getElementsByTagName('p')[0]
    const ul = document.getElementsByTagName('ul')[0]
  </script>
</html>

#javascript #dom #fundamentals

How To Traverse the DOM
1.35 GEEK