Document Object Model (DOM)

The Document Object Model (DOM) is a programming interface provided by browsers that represents the structure of an HTML document as a tree of nodes. It allows programming languages like JavaScript to interact with a web page's content, structure, and style.

Key Concepts of the DOM

  • Nodes and Elements: Everything in a document is a node, including elements, attributes, text, and comments.
  • Tree Structure: The DOM is organized in a hierarchical tree structure. The tree's root is the document object, representing the entire HTML document.
  • Access and Manipulation: JavaScript can access and manipulate the DOM, allowing dynamic changes to the content and structure of web pages.

Let's consider the following HTML page:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <div class="container">
        <p>Hello</p>
        <p class="highlight">World</p>
    </div>
</body>
</html>

This simple HTML document contains a div with two p (paragraph) elements. One of the paragraphs has a class named highlight.

For this HTML page, the DOM tree would look like this:

document
 └── html
      ├── head
      │    └── title ("DOM Example")
      └── body
           └── div (class="container")
                ├── p ("Hello")
                └── p (class="highlight", "World")

Each line represents a node, and the indentation represents the hierarchy. The document is the root node containing the html node. The html node contains head and body nodes, and so on.

I think the above tree looks a bit crap, so I created this Interactive DOM Visualizer where you can edit and paste in your code to better understand the DOM structure of your HTML.

Let’s break down the more detail so you can try understand this “tree” a little more:

  1. Document Node:

    • The root of the DOM tree.
    • Represents the entire HTML or XML document.
    • Provides properties and methods to access other nodes and elements within the document.
  2. Element Nodes:

    • Represent HTML tags such as <html>, <head>, <body>, <div>, and <p>.
    • Can contain other element nodes (child elements) or text nodes (actual text content).
    • Have attributes, such as classes or IDs, that provide additional information about the element.
  3. Attribute Nodes:

    • Provide additional information about elements.
    • Attributes are always part of an element node and cannot exist independently.
    • Examples include class, id, src, and href.
  4. Text Nodes:

    • Represent the actual text content within an element.
    • Text nodes are always leaf nodes in the DOM tree (nodes with no children).

Accessing the DOM

Here’s our first thing to do.

Jump into your browser and open the developer console where you can type things in and type the word document and tap the enter key.

  1. Opening the Console:

    • Chrome: Press Ctrl+Shift+J (Windows/Linux) or Cmd+Option+J (Mac).
    • Firefox: Press Ctrl+Shift+K (Windows/Linux) or Cmd+Option+K (Mac).
    • Edge: Press F12 and go to the "Console" tab.
    • Safari: Press Cmd+Option+C (Mac).
  2. Typing document in the Console:

    • Type document and press Enter.
    • You will see an object representing the entire HTML document.

A screenshot of developer tools open on the console tab. The output shows after a user enters “document" in the console. Then, you can see what looks like the HTML file in the console.

This may be a little different in each browser, but in Chrome you can see that you’ll see the document or HTML file directly in the console.

This document object is the bridge between HTML and JavaScript. By accessing this object, you can interact with and manipulate the structure and content of your web page. This is why understanding the DOM is crucial at the beginning of your JavaScript journey.

It allows you to create dynamic and interactive web experiences by modifying the HTML and CSS directly from your JavaScript code.

Here are some common methods or things you can to tag onto the document for accessing elements in the DOM.

document.getElementById()

Select an element by its ID. Since only one element can have a specific ID in a document, this method returns a single element. Example:

<div id="myId">Content</div>
document.getElementById('myId');

document.getElementsByClassName()

Selects all elements with a specified class name. This method returns a live HTMLCollection of elements. Example:

<div class="myClass">Content</div>
<p class="myClass">Another Content</p>
document.getElementsByClassName('myClass');

document.getElementsByTagName()

Selects all elements with a specified tag name. This method returns a live HTMLCollection of elements. Example:

<div>Content</div>
<div>Another Content</div>
document.getElementsByTagName('div');

document.querySelector()Selects the first element that matches a CSS selector. This flexible method can select elements based on any valid CSS selector.

Example:

<p class="highlight">Content</p>
document.querySelector('.highlight');

document.querySelectorAll()

Selects all elements that match a CSS selector. This method returns a static NodeList of elements. Example:

<div class="container">
    <p>Hello</p>
    <p class="highlight">World</p>
</div>
```js
document.querySelectorAll('.container p');

Exercise time

Find a webpage, inspect its HTML, and try to use each of these methods in the browser console to see their output. Remember to look through the HTML first to ensure there are IDs, Classes, or whatever you are looking for, or else you won’t get any response in the console.

Modifying elements

After learning how to access elements in the DOM, we can now focus on modifying these elements to change their content, attributes, and styles dynamically. Here are some things we can chain on further for modifying elements you selected:

textContent

The textContent property sets or returns the text content of a node and its descendants. Example:

<p id="myParagraph">Original Text</p>
document.getElementById('myParagraph').textContent = 'New Text';

innerHTML

The innerHTML property sets or returns the HTML content inside an element. Example:

<div id="myDiv">Original Content</div>
document.getElementById('myDiv').innerHTML = '<p>New HTML Content</p>';

style

The style property is used to get or set the inline style of an element. Example:

<p id="myStyledParagraph">Styled Text</p>
document.getElementById('myStyledParagraph').style.color = 'blue';
document.getElementById('myStyledParagraph').style.fontSize = '20px';

classList.add()

The classList.add() method adds one or more class names to an element. Example:

<p class="myClass">Text</p>
document.querySelector('.myClass').classList.add('newClass');

classList.remove()

The classList.remove() method removes one or more class names from an element. Example:

<p class="myClass anotherClass">Text</p>
document.querySelector('.myClass').classList.remove('anotherClass');

As you can see, modifying elements in the DOM allows you to create dynamic web pages by changing content, styles, and attributes on the fly. Later in the series, we will see how to do this with interactions on our webpage. But for now, know we can access and use everything in the DOM with JavaScript.


The DOM is a crucial concept for web development, acting as the bridge between HTML and JavaScript. Take some time to play with it, as it’s one of those concepts that can really help you excel as a JavaScript developer.

Next, we will explore values and data types in JavaScript.

JavaScriptBeginner
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.