...

/

Introduction to The Document Object Model

Introduction to The Document Object Model

Get an overview on the Document Object Model.

So far, we’ve mainly been interacting with our code in the console or by using pop-up boxes. Since the advent of the computer monitor, computer programs have been able to provide some kind of graphical user interface (GUI) to allow users to interact with programs. For example, operating systems such as Windows or iOS provide GUIs that allow us to interact with our computer or device.

Most programming languages will have a library that allows us to create a GUI. In a browser, we can use HTML and CSS to create a GUI for the user to interact with.

The Document Object Model, or DOM for short, allows us to access the elements of a web page from within our code. It provides tools for adding and removing elements, and for updating the content and style of a page.

The DOM is language agnostic, which means that it can be used in any programming language, although JavaScript is the language it’s most associated with. We’ll be focusing on using JavaScript to access the DOM here.

The Document Object Model

The Document Object Model represents an HTML document as a network of connected nodes that form a tree-like structure.

The DOM treats everything on a web page as a node. It represents HTML tags as element nodes and any text inside the tags as text nodes. All these nodes are connected to make a node-tree that describes the overall structure of the web page.

To demonstrate this, let’s take a look at the following short snippet of HTML code:

<h1 id='greeting'>Hello, <em>World!</em></h1>

This can be represented as the node-tree diagram shown below.

Press + to interact
The Hello, World! DOM
The Hello, World! DOM

The <h1> tag contains everything, so this appears as an element node (represented by purple ovals in the diagram) at the top of the node tree. The word “Hello” is text, so this is a child text node (represented by green rectangles in the diagram). The <em> element is inside the <h1> tag, so it’s a child element node. This makes the <h1> element node a parent node of these child nodes. The ...