HTML5 Document object model explained easy
HTML DOM Guide for Everyone

When you open a webpage, the parser of the browser starts immediately to process the underlying HTML-File. The content of the file is going to be converted into a tree structure, consisting of various nodes, such as element, attribute, and text nodes.

This newly created structure is then the basis for editing this web page. The editing is done by CSS and JavaScript. CSS applies styles and changes the look and feel of the page where's JavaScript is used to handle data and provide data. Generally spoken: You use both to access elements, change them, remove them, or link them to user interaction & other events.

All this is reason enough to inspect the Document Object Model (DOM), to understand its structure, and to inspect the central functions for access and processing.

The tree structure

The definition of the DOM gets defined by the W3C.[1] W3C describes DOM as a standard interface (API) for accessing the structure of documents. Making it easier for us as programmers to access components and edit, delete or add new content. It also allows us to create and change attributes and the elements' appearance. The current standard was already adopted in version 3 in April 2004 and accordingly fully implemented in all current browser versions.

The DOM is represented as a tree structure. The root of that structure is document and html as nodes and then splits into head and body. If you would like to look at how a website looks after parsing, the Live DOM Viewer service. is worth a visit.[2] It’s rudimentarily done, but the result is very visual. After copying the text of the HTML page into the top window, you will see the appropriate DOM representation (Figure 1).

Figure 1: Converts HTML input to tree-structure and shows the markup as displayed in the browser

The Chrome browser extension HTML Tree Generator (Figure 2) provides a fully visualized tree structure display. This illustrates the first picture of how your browser sees your HTML document. In the next step, you can concentrate on accessing and changing the individual elements via JavaScript.

Figure 2 showing the DOM-Tree with HTML Tree Generator Chrome Extension [3]

With HTML DOM, you have a standard object model and programming interface for HTML. I show you in the following example how to take actions against HTML nodes with DOM-Methods. To do so, we will use DOM-Properties. Those are specific values we can set and change. We use an HTML document displaying just a title and a bit of text.

To access the document object model, we will use JavaScript. That is possible because inside a model all HTML-Elements are defined as objects. We will change the content of the node <p> (paragraph) that displays “Inventory Content Display”.

Accessing the DOM-Elements

As you can see, the <p> tag got a property called id, and its value is P1. This is important because accessing an element with JavaScript needs an id when we are working with the method getElementById. We have to pass in the id for this element we want to get returned by the method.

Important to add the script after the <p>-node in the html file. If you set in before then we are accessing a paragraph that has not been parsed yet, leading to a null reference exception.

Opening this file with the browser and you see instantly how “Inventory Content Display” was changed with “This is the content of your inventory”.

InnerHTML grants you access to the HTML-Markup of that element you found with the getElementById function call. This applies to any html element, including <html> and <body>.

Accessing the global space of the document itself happens when you call the document-object. It is like the root you saw in the DOM-Tree and every other object inside this document is a child of the document object.

To access an element, different ways are likely. It depends on how much you know about it. The simplest way was the one in the first example: You know the ID and use it for direct addressing. If you are not sure if the element exists on the web page, you can easily check this. Adding the following lines to your script above to print out every piece of information about the HTML.

As long as it is existent in the HTML-Document, you can see the value for innerHTML, and much more important properties inside this list. For example, the next sibling, if it is draggable, and many more. (Figure 3)

Figure 3 Console Printout Part 1

Figure 3 Console Printout Part 2

Attention: In Firefox console.log only prints out a “toString” representation, whereas console.dir prints out a navigable tree. In Chrome, console.log already prints out a tree — most of the time. However, Chrome’s log still stringifies certain classes of objects, even if they have properties.

Elements access on HTML-Pages

The next example offers us the following view:

If you don’t know the exact name of the element you want to change, just search for a specific tag, like the paragraph. As you can see, I added up some more paragraphs to the document. Now we are searching for the two <p> tags:

For this, we use the getElementsByTagName method, as shown in the example. Since there are several paragraphs, the variable paragraphs contain an HTML collection. (Figure 4)

Figure 4 Console Printout of a document-object collection

From a technical point of view, this is an array, on which you can access by index, starting with 0 for the first element. With the following change of the script, you get the text of your second paragraph.

Leads to a console printout of our second paragraph. (FIGURE 5)

Figure 5 Console Printout of textOfParahgraph2

Alternatively, you can also process the individual elements of the HTML collection and print each text individually. The easiest way to do this is to use a for-loop:

The variable paragraphsText stores each paragraph's text into an array and i is the counter for the for-loop. The for-loop runs until the last index of the array is reached. The text is assigned via reading the innerHTML property. The output gets stored successively. For each entry of the array, and therefore the paragraphs innerHTML, we are printing out one line into the console. To achieve a line break when outputting to the console, “

” is used. This causes figure 6

Figure 6 console printout of the entire array with looping

Special offer for alternatives

JavaScript offers other methods to identify elements. You can access elements that have a specific CSS class. E.g. <h1 class=”title”>Header H1</h1>. getElementsByClassName(className) returns us those tags with the corresponding class. You determine the element via the following JavaScript code:

As in the previous examples, you can access the objects that have the class “title”. Depending on how you have built your HTML page, this can be quite a lot of elements. The result set can be further by using the CSS selector search. If you want to limit your result set to h1 headings, use the h1.title selector. During the search for the matching elements, you can use the method querySelectorAll.

Putting all pieces together results in our HTML file with the two JavaScript lines.

With these different access methods, you can modify a collection as we did in the last example.

More Interactions

In the first example of this article, I showed you how to access and modify the content of a paragraph (<p> tag). However, this can be done not only for simple texts but also we can easily modify headings or images. There are several objects inside the following HTML page, which are accessed via the DOM with the goal of customizing the content.

Opening the file in the browser will bring up this:

The initial state of the web page

The first step is to adjust the headline. The access via document.getElementById(). With the following script line, you assign new content to the heading:

The outcome will change to:

Changed the Header with the tag <h1> to “Ternoc’s Inventory”

In our next step, we are going to replace the image. Again, we use the ID for this. However, since in this case the value for the source is exchanged, the src property is adjusted. In the program code, this looks like:

And now we are open the corresponding inventory of Ternoc. (Compare picture profile, inventory content, and the title of the inventory window)

Last change of Headline & Inventory picture

This way, you access all elements of your website and dynamically adjust the values at runtime.

Change the look of your HTML page

We can go beyond classic HTML elements, such as a heading or an image. DOM also allows you to access the visual properties of an element. You will see how to access and adjust the color of a text using it.

If you open this HTML-File in the browser, only two lines of text appear on the web page at first.

In the next step, the first sentence with the ID toBeColored gets colored in orange directly when the page opens. To do this, use the style property and access the color via this property:

Insert the program lines at the end of the body tag area. If you open the document in the browser again, the first line appears colored in orange.

We couple the click event of a button with the visibility of a text that has been colored in orange before. We add a button that changes the visibility of the text. We do an inline function as the value assignment for the property onclick. Since we want to represent access to the properties of the two elements:

We access the text as before via getElementById, but now the Id was changed to “toBeInvisible”. You change the visibility via the style-property visibility. In addition, the text of <input> is to be adjusted. To do this, the element is accessed via getElementsByTagName and the element and adjust the caption via value.

Finally, we are going to add a second button that engages the font color to change to red by clicking on it. Additionally, the visibility of the text is adjusted, if it should be invisible:

This is the corresponding HTML-File.

As you have seen from the examples, you can access the individual style properties directly, just as with CSS. I clicked on the button to make the text invisible and the text of this button changed to “The text is invisible now.” (Figure 8). After that, I changed the text to red. Although the text was invisible, we colored it to red, anyway. That's because we set the visibility property back to visible.

Navigating the DOM

We have already seen how the DOM represents the structure of an HTML page: document and HTML are the root nodes, all other elements are children to them. In the previous examples, we have defined access to the elements either by ID, tag, or CSS class. However, DOM also allows you to navigate through the tree structure from node to node. For this you have different properties, like parentNode, childNodes[], firstNode, or lastNode. We will see in the following examples how to use them to navigate to the appropriate element in your web page.

With the corresponding markup file:

The property firstChild represents the object itself. If you query the node value of the element with the Id H1, you will get — Navigation via nodes as a response.

Brings up the same result as:

Another way to achieve the same return is to access via index:

All three accesses lead to the same result. Of course, you can navigate the tree from top to bottom, but also pass through in the other direction. The parentNode property is available for this purpose. If you move up one node, starting from the H1 heading, you will end up at the div tag. The current name of the node that you are currently accessing is output via nodeName:

If you then output parentNode via the console, you will see that the parent element in our example is the div tag. Of course, you can also make assignments of values via this route. For example, if you use the div tag to assign the color to the child elements, the code line would look like this:

Putting now all pieces together will bring us the following HTML-File:

With the shown commands, a navigation up and down in the tree is possible to manage the color change to blue.

Create additional elements and nodes

Again and again, it is necessary for the practice of web design, to create additional elements and nodes in your DOM using a script. We can easily do this with JavaScript.

As a starting point, we will use the HTML page from the previous example, but without the script. The goal should be to insert a new sentence before the paragraph. The process is multi-step within JavaScript:

We create a new element and a new text node. We link this using the appendChild() function. We need to determine a reference point for inserting the newly generated element. The first option is to append it directly within the paragraph as a new element at the end. For this, we use the appendChild() function again.

When you open the page with the script, you will see the new sentence inserted below “The text of the new node.”. This happens automatically since the script will be executed directly after the browser loaded the HTML-file.

Changing the code to a function and adding a button calling that function, which is nothing new to you. You’ve already seen this in X4_2_ActionButton & X4_2_ActionButton2. This time instead of having Javascript defined inline, we encapsulate it into a function (callable by many buttons for example) and run it like you already seen by onClick.

Each click will insert an additional element after the next one. The DOM tree gets additional elements appended, compare to the figure, to comprehend how many times I’ve clicked the button.

You can also specify the position for insertion more precisely, for example, before a particular line. We insert the new sentence directly below the heading and with the button example direct after the button. To do this, you need both the div tag with ID D1 and the paragraph with ID P1 as reference points. Once you have all the information together, you can insert the new element with a call of the insertBefore-Method:

Here, we will insert the new text right after the heading, before the reference of childNode. We recolor the text to green to be spotted easier.

Delete elements

There is not only the possibility to add elements, but also to delete them. For this purpose, you use the remove() function. We extend the previous example and delete the originally existing paragraph with the Id P1. For this you need again first a variable as a reference, which you use in the second step to delete the element:

Hitting the button…

…will cause a vanished button.

Node replacement

A third possibility, besides creating and deleting, is to replace an existing element with a new one. In the last example, the newly created sentence is to replace the existing paragraph.

To do this, first create the new sentence again, as shown before, and determine the reference point of the element that is to be replaced via the div tag and the ID of the paragraph. The replacement takes place via the replaceChild() function:

This HTML file makes the browser to displace this:

If you brave enough to push the button, you’ll see the difference:

Conclusion

As you have seen from the examples, accessing elements, and managing them using DOM and JavaScript is as simple as can be. Access works reliably via the ID of the various elements, but we can also implement navigation via parent and child nodes with no problems.

Follow ~1600 students and get my free C# Course Explained by Games

Read On

References

[1] W3C https://www.w3.org/

[2] LiveDomViewer https://software.hixie.ch/utilities/js/live-dom-viewer/

[3] HTML Tree Generator https://chrome.google.com/webstore/detail/html-tree-generator/dlbbmhhaadfnbbdnjalilhdakfmiffeg/related
['Arnold Abraham']
['Software Development', 'JavaScript', 'Frontend', 'HTML', 'Web Development']