The Document Object Model
Tags: beginners, javascript
Published: 2020-01-03 10:44:01

---
title: The Document Object Model
published: true
description: An introduction to the Document Object Model
tags: beginners, javascript
series: FrontEnd Development Zero to Hero
---
Documents are everywhere, from our offices,  schools to our homes. A document can be anything ranging from _business proposals_ to _textbooks_ and with the advent of the web, you'll find some documents in hard copies and soft copies available for purchase on eCommerce platforms like Amazon.

There are varieties of documents on the web, but the one we are concerned with in this post is the Hypertext Markup Language (HTML) document most especially, how the web browser parse and interpret the document under the hood.

Now, you might ask: How is this related to the title of the post &mdash; The Document Object Model? Everything.

The Document Object Model or DOM for short, comprises of three words which are:

* Document
* Object
* Model

In this context the _document_ is our __HTML document__, the _object_ are the __HTML tags__ and the _model_  is the __document structure__. Say what?.

To be candid, this definition is quiet basic and I hope you get the point. As we'll see later there is more to the DOM.

Let's dive in and find out.

_All screenshots are from <b>Firefox 71.0</b> and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the <b>multi-line code editor</b> in the console._

<hr>

From a beginners perspective, when you come across the DOM for the first time, you will have a lot of questions. I took the liberty of assuming some of these questions. The questions are listed in an order i think you might ask them. Each question (excluding the first one) will be the continuation of the preceding question. The questions are <a name="dom-questions"></a>:

* [What is the DOM?](#what-is-the-dom)
* [Will the browser fix some errors in my HTML?](#browser-fix-errors)
* [How can i access the DOM?](#access-dom)
* [Can i access the DOM without the browser _Developer Tools_?](#access-dom-online)
* [How can i find elements in the DOM?](#find-elements)
* [How can i manipulate the DOM?](#manipulate-dom)
* [Is it possible to create an element in the DOM?](#create-element)
* [Is it possible to style an element in the DOM?](#style-element)
* [Can i query the DOM?](#query-dom)

Let's answer these questions one after the other.

###__What is the DOM? <a name="what-is-the-dom"></a>__

From a theoretical point of  view, __the DOM is a language agnostic interface__ that allows a programming language to manipulate the content, structure and style of any website.

There are two phrases that might be blurry from the last paragraph. They are:

* language agnostic
* manipulate the content, structure and style

The term _language agnostic_ means the __DOM is created to be independent from a particular programming language__. This post will focus on the JavaScript implementation of the DOM. Implementation? That's because the DOM has its own [specification](https://dom.spec.whatwg.org/) available online for any interested party.

When we talk about _manipulating the content, structure and style_ of a website, this means __we can use some methods or API's available in JavaScript to alter the web page__ and the page is updated to reflect the changes which makes the DOM act like a _live_ data structure.

From a practical aspect, __when you navigate or open a web page in your web browser, the web browser parses the HTML and CSS and creates a representation of the document__. This representation is __known as the DOM__.  JavaScript can access this representation in the form of __objects__. Let's have a  look.

```html
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Document Object Model</title>
</head>
<body>
  <h1>This is an header</h1>
  <p>This is a paragraph text</p>
</body>
</html>
```

Use "Inspect Element" on the _paragraph text_, the _Developer Tools_ will come up and what you see under the __Inspector__ tab is a _close representation_ of the DOM. Why i said it's a _close representation_ is because the _Developer Tools_ can contain additional information like _pseudo-elements_.

![A close representation of the DOM shown in DevTools](https://thepracticaldev.s3.amazonaws.com/i/a8w7dj0ulfr1vubcyik0.PNG)

Humans are not perfect and you might unknowingly omit some tags in your HTML. Which brings us to the next question.

[[Back to questions](#dom-questions)]

###__Will the browser fix some errors in my HTML? <a name="browser-fix-errors"></a>__
Yes. During _parsing_ if the browser encounters malformed HTML like omitted tags, the browser will fix it. When you place a tag after the closing `</body>` tag, the browser will move the tag before the closing `</body>` tag.

Switch to your editor and __delete__ the closing `</p>` tag. Save and refresh your browser. You will notice the browser added the deleted closing `</p>` tag.

![An omitted tag fixed by the browser](https://thepracticaldev.s3.amazonaws.com/i/35diyjwvg3lq63izfzn5.PNG)

When you check the source of the page with `viewsource` you will notice the error.

![An omitted tag shown in viewsource](https://thepracticaldev.s3.amazonaws.com/i/505b54bz9g6ea4xydn0y.PNG)

Another instance of fixing errors is when you place a tag after the closing `</body>` tag.

Update your HTML by __placing the paragraph after__ the closing `body` tag.

Save and refresh your browser.

![A paragraph text placed before the closing body tag](https://thepracticaldev.s3.amazonaws.com/i/esahf1fmfiyhtmry6g7k.PNG)

Likewise you can use `viewsource` to check.

![An misplaced tag shown in viewsorce](https://thepracticaldev.s3.amazonaws.com/i/z7bdkyw3pt7deoxn71qq.PNG)

These are just two cases, __I'll encourage you to break your HTML__, refresh the browser and take note of the output in the _Developer Tools_ and browser `viewsource`.

[[Back to questions](#dom-questions)]

###__How can i access the DOM? <a name="access-dom"></a>__

__You don't need any special tool__ to access the DOM. The `document` object is a built-in object that has properties and methods that we can use to access and modify websites. 

![The document object shown in Firefox 71.0 DevTools](https://thepracticaldev.s3.amazonaws.com/i/uvfjifzr4ur531vupv1l.PNG)

If you are using Chrome your output will be similar to the image below.

![The document object shown in Chrome DevTools](https://thepracticaldev.s3.amazonaws.com/i/zdikpqiigtkxm98jcfei.PNG)

[[Back to questions](#dom-questions)]

###__Can i access the DOM without the browser Developer Tools? <a name="access-dom-online"></a>__

Yes you can. Using an online tool called [live DOM viewer](http://software.hixie.ch/utilities/js/live-dom-viewer/) by [Ian Hickson](https://github.com/Hixie).

Access the website linked above, __copy and paste__ the HTML in this post into the first text input labelled __Markup to test__ and the __DOM view__ section will show the DOM.

![Live DOM viewer](https://thepracticaldev.s3.amazonaws.com/i/6hsez1ldvwzd22kc4vmv.png)

[[Back to questions](#dom-questions)]

###__How can i find elements in the DOM? <a name="find-elements"></a>__

Methods and properties of the `document` are used to find elements in the DOM.

For this example we'll make use of the `document.getElementsByTagName()` method. __This method takes an HTML tag as an argument__ and returns an `HTMLCollection` which contains all the tag the method could find.

Type the following into the console:

```javascript
// look for all 'p' tag
document.getElementsByTagName('p');
```

The output:

![Finding Elements in the DOM](https://thepracticaldev.s3.amazonaws.com/i/ztgem5cx3y7qfmklgdi6.PNG)

You can click the arrow to see more details.

![Finding Elements in the DOM](https://thepracticaldev.s3.amazonaws.com/i/h47xnc5nxsyh5jntukf9.PNG)

Another method is the `document.getElementsByID()`. To the best of my understanding the name of the method should let you know how this method works &mdash; it simply look for an _id attribute_ in your HTML source code.

Modify your code by adding an ID attribute to the `<h1>` tag.

Then you can use the following code to get the ID:

```javascript
/**
  * Type the code into the console
  */

// look for element with the header tag
document.getElementById('header');  
```

[[Back to questions](#dom-questions)]

###__How can i manipulate the DOM? <a name="manipulate-dom"></a>__

I mentioned earlier that the DOM is like a _live_ data structure. This means any changes to the DOM is reflected immediately.

```javascript
/**
  * Type the code into the console
  */

document.body.style.backgroundColor = 'brown';
```

The output in the console after the enter key is pressed:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ibsuf44tg10393mfq04h.PNG)

[[Back to questions](#dom-questions)]

###__Is it possible to create an element in the DOM? <a name="create-element"></a>__

Yes you can. The `document.createElement()` is used to create an HTML tag which can be added to the DOM. It takes an HTML tag as an argument.

First update your HTML by adding an _id attribute_ with the value of `body`. 

This would be:

```html
<!-- all other content remain the same -->

<div id="body">

<!-- all other content remain the same -->

```

Now, take a look at the following code, and please do read the comments.

```html
<!-- copy/type this code after the paragraph in your HTML -->

<script>
  // get the body
  let body = document.getElementById('body');

  // create a div tag 
  let divider = document.createElement('div');

  // create a paragraph tag
  let paragraph = document.createElement('p');

  // add some text
  paragraph.textContent = "HELLO I WAS CREATED DYNAMICALLY";

  // append the paragrph to the newly created
  // div
  divider.appendChild(paragraph);

  //  append the div to the body
  body.appendChild(divider);
</script>
```

Save your HTML file and refresh your browser.

![Content added dynamically in the DOM](https://thepracticaldev.s3.amazonaws.com/i/9e89fafegcjsuul2tq1m.PNG)

[[Back to questions](#dom-questions)]

###__Is it possible to style an element in the DOM? <a name="style-element"></a>__

Of course you can! If an HTML tag has a `style` attribute we can manipulate it with JavaScript.

Update the `<p>` tag to match the following:

```html
<!-- all other content remain the same -->

<p style="color: green; font-weight: bold;">This is a paragraph text</p>

<!-- all other content remain the same -->
```

When you load the file in the browser, the text color will be green and the `font-weight`, bold. 

Time for some manipulation.

Delete the code  inside the `<script>` tag then add the following:

```javascript
/**
  * The method document.getElementsByTagName returns
  * an HTMLCollection. We grab the first paragraph
  * using the index number. If you are not familiar
  * with this syntax, please read the post on arrays
  * at https://dev.to/ziizium/javascript-arrays-50c5
  */

// grab the paragraph
let paragraph = document.getElementsByTagName('p')[0];

// change the color to red using the style attribute
paragraph.style.color = "red";
```

Save and refresh your browser.

![DOM manipulation](https://thepracticaldev.s3.amazonaws.com/i/e50vlc34swbkfvwtr752.PNG)

[[Back to questions](#dom-questions)]

###__Can i query the DOM? <a name="query-dom"></a>__

Yes you can. The `querySelectorAll()` takes a selector string and returns a `NodeList` of matching elements. Its cousin `querySelector()` takes a selector string and returns a single matching element.

__Add multiple paragraphs to your HTML__ with a `class` of `helloParagraph`.

The code below will return all the paragraph with a class of `helloParagraph`. You can type the code in the _console_ or in the `<script>` tag in your HTML.

```javascript

// get all paragraph with a class of helloParagraph
let helloPargraph = document.querySelectorAll('.helloPargraph');

// log the output
console.log(helloPargraph);
```

The output in the browser:

![querySelectorAll in Action](https://thepracticaldev.s3.amazonaws.com/i/ysbywgqe6rmywzw6x6cv.PNG)

[[Back to questions](#dom-questions)]

<hr>

We've covered a bit of ground here but there other things you can do in the DOM. 

They include:

* Dynamically adding CSS
* Manipulate page layout

If you'd like to take a deep dive into this entire subject, the following resource should help:

* [What, exactly, is the DOM?](https://bitsofco.de/what-exactly-is-the-dom/)
* [The Document Object Model :: Eloquent JavaScript](https://eloquentjavascript.net/14_dom.html)
* [Introduction to the DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)
* [What is the Document Object Model?](https://www.w3.org/TR/WD-DOM/introduction.html)
* [DOM Enlightenment](http://www.domenlightenment.com/)

And here on [DEV](https://dev.to):

{% link https://dev.to/aumayeung/introduction-to-dom-manipulation-54c1 %}

Up next, Ajax.