A friend of mine asked me the other day what the DOM is.
So what is the DOM exactly?
To make it easier to understand, we can use the tools provided with nearly every browser. In particular: the inspection tool and the “View Source Code”.
On your desktop you can hover this page with your mouse pointer and then click right to open the selection box.
On FireFox you will see the option “Inspect Element”, on Chrome probably just “Inspect”. You will also see on both “View Page Source”.
I will call the Inpect tool from now on “IT” and the View Page Source “VPS”.
Alright! Let’s start!
We have a table here that I have build using simple HTML, like so:
<table border="1"> <tr> <td id="my-dom-td" style="text-align:center;">THIS IS MY CONTENT</td> </tr> </table>
This is indeed all I have written, and here it is:
|THIS IS MY CONTENT|
Now let’s use the VPS: (click right on your mouse / touchpad and select “View Page Source”):
What you are looking at now is the HTML of the page. Search for “THIS IS MY CONTENT” and you should find it 3 times. The first will be where I explain the code, the second will be the table itself with the text in it, and the third are the 4 words in this sentence. If you look at the second one, you will see that it sits inside the table the same way as I have explained it just above. The VPS shows you HTML mostly as it has been written originally.
Now let’s go onto the page again, click right on the mouse and choose this time the Inspect tool, the IT. Best is to have your mouse pointing directly over the table itself.
So what do you see now?
The table is there again, but wait!! …. there is this
Now you are looking at a representation of the DOM, the rendering of HTML. It looks like HTML, but it has some more to it. It is an interface, more precisely, an API (Application Programming Interface) with which you can interact and which acts by itself in some cases, like before, when it is simply adding the “required” <tbody> to the table I have build.
<button onclick="document.getElementById('my-dom-td').innerHTML=Math.floor((Math.random() * 1000));">Click Me and Check the table above</button>