DOM (for Document Object Model) is a way of conceptualizing and structuring the content of a web page. You can think of this as an agreed-upon method to describe document elements and their relationship to each other, just as there is an agreed-upon way of describing houses on a street. We all acknowledge, for instance, that the long strip of tarmac dividing houses on one side from the other is called the “road”. Each house is numbered, but we might also address them by position: “The third house on the left”, for example, or “The house after the red house”. While each house or building will be entered in a slightly different way, we address that entryway using the same name: “door”.
Through A Mirror, Darkly
The DOM is a reflection of the foundational HTML on a page: the DOM cleans up the HTML and allows you to make changes to it in real time. For example, create an HTML page with the following code:
<!doctype html> <html lang=en> <title>DOM Example Page</title> <main> <p>Text content </main>
This is perfectly valid HTML5 code. Bring the page into a browser, right-click on the text, and choose Inspect Element. The result, shown using the browser's Developer Tools, will look something like this:
<html lang="en"> <head> <title>DOM Example Page</title> </head> <body> <main> <p>Text content </main> </body> </html>
The DOM is what the browser “thinks” of the page: as a first step, the DOM API cleans up the code it is given to the best of its ability, ensuring that all tags are closed and all attribute values are quoted. This doesn't mean that the code we initially created is “wrong” in any sense, only that the DOM’s understanding of the page is more precise: you might think of it as the difference between an architect's sketch of a house and a fully detailed engineering plan of the same structure.
Manipulating The DOM
While looking at your page in the browser window, switch to the Console tab in Developer Tools and type the following:
document.querySelector("main p").innerHTML = "new content";
Take a look at the page, and then switch back to the Inspect Element tab. You’ll see that the page and DOM have changed, reflecting your new content. However, the actual source code has not: you can prove this by right-clicking on the page and choosing View Source, where you will see your original code, unchanged.
Illustration by Rachel Nabors, used with permission
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.