What is the DOM in JavaScript?

OpenJavaScript 0
Reading Time: 6 minutes 🕑

Last updated: April 11, 2022.

The DOM is an abbreviation for ‘Document Object Model’. It may sound abstract at first, but the DOM is actually a very concrete entity. It is through the DOM that you can reach into a web page from JavaScript and edit its contents.

Not wanting to throw more confusion out there, but, technically speaking, classed as an Application Programming Interface (API). This is because it ‘interfaces’ between JavaScript and the browser in jointly maintaining a web page.

So the DOM is far more than an abstract concept: it helps JavaScript to fulfil its central task of manipulating web pages.

In this article, we provide a beginner-friendly demystification of the DOM, focusing on its use in practice.

Where is the DOM? Can I view it?

Yes! The ‘document object’ part of the DOM exists in JavaScript.

You may already be familiar with methods that exist on the document object, such as document.getElementById() and document.getElementsByClassName(). These methods are stored on it.

So to access the document object directly, simply pass the object into a console log:

/* Log the contents of the document object to the console */

console.log(document);

In Chrome, this will log a live representation of the HTML document it is linked to in the browser.

This is the document part of ‘document object’, and it is maintained jointly by JavaScript through this object and updated live in the browser.

Note that in some browsers, you may need to call console.log(document.body) to access this live view. This is because the document object also contains properties and methods for managing the document. The body accesses the document directly.

Representation of the DOM as JavaScript output

Is the DOM just an object?

From the perspective of JavaScript, the document object is just an object.

The only difference is that changes to the document object are reflected in the browser. Hence, the 'model' appendage.

It also has special methods attached to it that allow you to manipulate its contained document (e.g. getElementById(), append(), remove()). But you interact with it like any other object in JavaScript.

The document in the browser

A live representation of the document is, of course, also maintained in the browser: both the HTML nodes and elements as well as being rendered as a page, so users can interact with it.

Casually, this is often referred to as the DOM as well, even though the object is only accessible via JavaScript.

The browser offers a much easier way of viewing the contents of the document: open inspector tools (CTRL+SHIFT+I in Chrome) and click on the Elements tab. Unlike console.log(document), which must be called again to see updates, this is a live view of the document. You do not have to refresh to see changes.

Live representation of the DOM in the browser

Is the DOM just my HTML markup?

For a static page, HTML markup and the document part of the DOM look almost identical:

<!--- Original markup --->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>My Document</h1>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vel non quo consequuntur consectetur, assumenda voluptatem magnam aliquam dolore molestias totam ipsa placeat? Odio, consequuntur nihil. Eos alias quis ipsum minus.
    Suscipit impedit qui quod, neque iste nam. Quis, exercitationem voluptas nobis ex facere ipsa eaque fugit dolor sit unde, modi consectetur eligendi laborum incidunt non impedit repudiandae temporibus numquam assumenda.
    Rem expedita optio culpa non quasi sit nostrum architecto dolor quisquam aperiam obcaecati iure magni, accusantium deserunt commodi sequi iste a adipisci molestias nisi veniam dolores quod perspiciatis. Sit, inventore.</p>
    <script src="script.js"></script>
</body>
</html>

This raises an obvious question: Is the DOM just a rendering of a HTML document in the browser?

The answer is no. The difference is that the browser and JavaScript jointly maintain a live representation of the document. Our HTML markup is static.

But, if there is no dynamic content, the live DOM representation will look just like the original HTML document. Like in the example above.

But if we insert some new content using JavaScript, the DOM representation will start to diverge from the HTML:

/* script.js makes a small addition to the body of the document */

const article = document.createElement('article');

article.innerHTML = `
<p>Aut nisi consequatur 33 magni perspiciatis nam aperiam doloribus eos consequatur officia! In natus esse non dolores eveniet est perferendis praesentium vel animi sequi eos totam amet est nobis voluptatem. Est dolores omnis sed doloremque odit eos consequuntur fuga et exercitationem voluptatem est reiciendis consequuntur aut repudiandae ullam. At aliquam quia in explicabo voluptas qui autem sapiente ut veritatis consequuntur et libero facilis.</p>
`

document.body.append(article);

And here's what the document now looks like in the browser:

A slightly modified document vs the original HTML markup

So the document in the document object model now diverges (though not very significantly) from the original HTML markup: there is a new article element containing a paragraph.

You can think of HTML as a starting point for the DOM. But once there is dynamic content, the document produced by the DOM can look significantly different from the original markup.

When HTML and DOM are very different

The state of the DOM can sometimes differ wildly from the original markup.

For example, in modern web apps, it is typical to start with a single HTML element into which content is dynamically injected (think content of social media timelines, for example).

We won't be designing and implementing a web app here. But we can change our markup to demonstrate this kind of significant change through the DOM.

Here's some basic markup:

<!--- Minimal markup --->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <div id="myApp"></div>
   <script src="script.js"></script>
</body>
</html>

Now, in script.js, we could insert some content into the empty myApp div:

/* script.js injects all visible content into the 'myApp' div element*/

const app = document.getElementById('myApp');

app.innerHTML = `
<h1>Content inserted from JavaScript</h1>
<main>
  <article>
    <h3>Article 1</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia provident quibusdam consequuntur dolor reprehenderit itaque porro perferendis eos odio enim, earum nam blanditiis fugiat voluptates modi facilis impedit dignissimos laboriosam?
    Molestias reprehenderit quidem voluptas perferendis iure pariatur culpa nisi! Odio, totam! Alias quae nostrum odit quia autem eveniet eum saepe, distinctio quam fuga veniam ducimus libero. Accusamus voluptatum sunt blanditiis.
    Impedit accusantium harum, iste deleniti minus, reiciendis rem aliquam odit quos animi mollitia ratione cum doloremque saepe maxime corrupti perferendis adipisci ipsam, soluta ex maiores quod quo! Exercitationem, vero accusamus?
    Quas iste nam, dolorem qui quod exercitationem deleniti eos molestiae, suscipit dolorum illum corrupti. Itaque, eaque laborum, maiores officiis, nostrum eligendi facere minima fugiat molestiae deleniti reprehenderit autem quae doloribus.
    Modi quidem illo minus consequatur quis quas doloremque ratione, expedita corrupti facere aliquid accusamus totam in saepe distinctio dolorum ducimus cumque dolores maxime ad possimus tempora facilis assumenda? Laborum, optio!</p>
  </article>
  <article>
    <h3>Article 2</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia provident quibusdam consequuntur dolor reprehenderit itaque porro perferendis eos odio enim, earum nam blanditiis fugiat voluptates modi facilis impedit dignissimos laboriosam?
    Molestias reprehenderit quidem voluptas perferendis iure pariatur culpa nisi! Odio, totam! Alias quae nostrum odit quia autem eveniet eum saepe, distinctio quam fuga veniam ducimus libero. Accusamus voluptatum sunt blanditiis.
    Impedit accusantium harum, iste deleniti minus, reiciendis rem aliquam odit quos animi mollitia ratione cum doloremque saepe maxime corrupti perferendis adipisci ipsam, soluta ex maiores quod quo! Exercitationem, vero accusamus?
    Quas iste nam, dolorem qui quod exercitationem deleniti eos molestiae, suscipit dolorum illum corrupti. Itaque, eaque laborum, maiores officiis, nostrum eligendi facere minima fugiat molestiae deleniti reprehenderit autem quae doloribus.
    Modi quidem illo minus consequatur quis quas doloremque ratione, expedita corrupti facere aliquid accusamus totam in saepe distinctio dolorum ducimus cumque dolores maxime ad possimus tempora facilis assumenda? Laborum, optio!</p>
  </article>
</main>
`

The DOM now looks very different from the original markup:

A radically modified document vs the original HTML markup

In this example, the new content is hard-coded. In practice, this would likely be imported by making an API call.

Summary

The concept of the DOM (Document Object Model) can be confusing, especially for beginners.

But in practice, from the perspective of JavaScript, it refers to an object like any other: the globally available document object. But, unlike other objects, changes to this object are reflected in the browser.

The 'model' part of the DOM refers to the fact that the browser and JavaScript jointly maintain communication about the contents of a web page via this object. As such, the document object is JavaScript's gateway to this live document.