What is the DOM? A very quick intro to the Document Object Model

What is the DOM? A very quick intro to the Document Object Model

Once you've learned a bit of HTML and CSS, you're probably ready to move on to adding some interactivity to your website, using JavaScript. Before you start, it's helpful to understand a bit more about the Document Object Model, a.k.a. the DOM.

So what is the DOM?

The Document Object Model, or DOM, is a thing created by the browser - it essentially organises your HTML file into a structure that's a bit like a family tree.

You don't 'see' this tree-shaped DOM but once it has been created by the browser, it then sits between your HTML file and the script file (e.g. your .js JavaScript file) and allows JavaScript to access, modify and update the webpage. We can also use Chrome's Developer Tools to look at a version of the DOM (more on this later).

From Codecademy: "The DOM is a logical tree-like Model that organizes a web page's HTML Document as an Object."

The DOM follows the same hierarchy as the HTML document - for example, it shows that a div is a child of the body element, and that the paragraphs within that div are children of the div.

Here's a diagram that takes an HTML file and turns it into the DOM:

HTML-to-DOM.png

In the diagram above, each of the HTML elements becomes a 'person' on the family tree - each 'person' is known as a node. The nodes also hold other information about things we have assigned to an element, such as style or id.

Want to see the DOM in action?

Open Google Chrome and go to your favourite webpage (or open one using an HTML file you've created yourself). Right click anywhere on the page and click 'inspect'. This will open up the Chrome Developer Tools window. The orange box in the image below shows you how the DOM is represented in Chrome Dev Tools:

chrome-dev-tools-dom.png

You won't see a family-tree diagram, but you will see all the HTML code that sits behind that particular website. You can even click on and (temporarily) edit the webpage. This is you changing the DOM! Refresh the page and you'll see that it reverts back to the original site, but it's a fun and useful tool for playing around with the website and trying out changes before making them permanent.

So there you have it - a very quick intro to the DOM.