Document Object Model (DOM)

DOM stands for Document Object Model.

When we send HTML to a browser, the browser renders the HTML (displays it in a window) and it also creates a giant object that represents the web page. As web developers, we can interact with this object (DOM) and make changes to the it without modifying the actual source code. The browser will redraw the web page to reflect any change we make to the DOM.

DOM Tree

Given this HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM Tree</title>
  <script src="main.js"></script>
</head>
<body>
  <h1>Doggos</h1>
  <div class="container">
    <img src="https://placedog.net" alt="random dog" />
    <h3>The goodest doggos</h3>
    <ul>
      <li>Tonto</li>
      <li>Sailor</li>
      <li>Scout</li>
      <li>Odin</li>
      <li>Poppy</li>
      <li>Peggy</li>
    </ul>
  </div>
</body>
</html>

The HTML's structure (nested tags, etc.) can be visualised as a tree in the DOM:

  • The head and body are children of the document

  • The body is the parent element of the h1 and the div with a class of container

  • The h1 element and the container element are siblings

  • The li elements are also siblings of each other

  • What relationship does the image have with the h3? What about the image and the div with the class of container?

Being able to relate and navigate the different elements in this way is often referred to as 'traversal' and there are JavaScript methods that will help you access the element you want. Oftentimes you'll want to target the child elements or the parent element, rather than the element itself. This will become more apparent as you start to build more complex things.

Nodes vs Elements

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created to hold a block of text inside an element. So, in a nutshell, nodes are any DOM object while elements are the HTML elements.

The DOM tree diagram above is a simplified tree that only shows the element nodes. A more complete DOM tree will look like the following:

This tree shows the text nodes including comments and the whitespace in the HTML file (line breaks and indentation).

DOM Tree visualisers:

Last updated