FrontEnd Development Zero to Hero (65 Part Series)
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:
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 :
- What is the DOM?
- Will the browser fix some errors in my HTML?
- How can i access the DOM?
- Can i access the DOM without the browser Developer Tools?
- How can i find elements in the DOM?
- How can i manipulate the DOM?
- Is it possible to create an element in the DOM?
- Is it possible to style an element in the DOM?
- Can i query the DOM?
Let's answer these questions one after the other.
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
<!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.
Humans are not perfect and you might unknowingly omit some tags in your HTML. Which brings us to the next question.
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
Switch to your editor and delete the closing
</p> tag. Save and refresh your browser. You will notice the browser added the deleted closing
When you check the source of the page with
viewsource you will notice the error.
Another instance of fixing errors is when you place a tag after the closing
Update your HTML by placing the paragraph after the closing
Save and refresh your browser.
Likewise you can use
viewsource to check.
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
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.
If you are using Chrome your output will be similar to the image below.
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.
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');
You can click the arrow to see more details.
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
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');
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';
The output in the console after the enter key is pressed:
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
This would be:
<!-- 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.
<!-- 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.
Of course you can! If an HTML tag has a
<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 -->
When you load the file in the browser, the text color will be green and the
Time for some manipulation.
Delete the code inside the
<script> tag then add the following:
Save and refresh your browser.
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
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);
The output in the browser:
We've covered a bit of ground here but there other things you can do in the DOM.
- 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?
- Introduction to the DOM
- What is the Document Object Model?
- DOM Enlightenment
And here on DEV:
Up next, Ajax.