DEV Community

Habdul Hazeez
Habdul Hazeez

Posted on

The Document Object Model

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 — 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 Firefox 71.0 and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the multi-line code editor in the console.


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 :

Let's answer these questions one after the other.

What is the DOM?

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 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.

<!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>
Enter fullscreen mode Exit fullscreen mode

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

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

[Back to questions]

Will the browser fix some errors in my HTML?

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

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

An omitted tag shown in viewsource

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

Likewise you can use viewsource to check.

An misplaced tag shown in viewsorce

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]

How can i access the DOM?

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

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

The document object shown in Chrome DevTools

[Back to questions]

Can i access the DOM without the browser Developer Tools?

Yes you can. Using an online tool called live DOM viewer by Ian Hickson.

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

[Back to questions]

How can i find elements in the DOM?

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:

// look for all 'p' tag
document.getElementsByTagName('p');
Enter fullscreen mode Exit fullscreen mode

The output:

Finding Elements in the DOM

You can click the arrow to see more details.

Finding Elements in the DOM

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 — 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:

/**
  * Type the code into the console
  */

// look for element with the header tag
document.getElementById('header');  
Enter fullscreen mode Exit fullscreen mode

[Back to questions]

How can i manipulate the DOM?

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

/**
  * Type the code into the console
  */

document.body.style.backgroundColor = 'brown';
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

[Back to questions]

Is it possible to create an element in the DOM?

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:

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

<div id="body">

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

Enter fullscreen mode Exit fullscreen mode

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

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

Save your HTML file and refresh your browser.

Content added dynamically in the DOM

[Back to questions]

Is it possible to style an element in the DOM?

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:

<!-- 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 -->
Enter fullscreen mode Exit fullscreen mode

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:

/**
  * 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";
Enter fullscreen mode Exit fullscreen mode

Save and refresh your browser.

DOM manipulation

[Back to questions]

Can i query the DOM?

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.


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

// log the output
console.log(helloPargraph);
Enter fullscreen mode Exit fullscreen mode

The output in the browser:

querySelectorAll in Action

[Back to questions]


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:

And here on DEV:

Up next, Ajax.

Top comments (2)

Collapse
 
jlrxt profile image
Jose Luis Ramos T.

Gracias/ leyendo en el viaje devuelta a casa. Extraño mi pc. Ahora tengo una noción del DOM .

Collapse
 
ziizium profile image
Habdul Hazeez

De nada.