What Is The DOM?

There is no starter file required for this lesson.

Introduction

Welcome to this new section. Things are going to get a lot more interesting from here in terms of what we see in the browser.

Most of the examples we have used have made use of the console, and this is a great way to see a result. But, what we ultimately want is to see things happen in the browser. We want to create and update the data or the elements on a web page.

We have briefly looked at a way of doing this earlier, but this new section is going to cover so much more, and by the end of it, you will know the full power that JavaScript can have over our web pages.

The DOM Tree

Just before we jump into some code it is important to know about something called the DOM. The DOM stands for Document Object Model and is a programming interface for our HTML pages.

The DOM represents our web page in a tree like structure. It is creating a map of our web page from the top-level elements, right down to the bottom.

Here is a basic HTML document:

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <h1 id="">Hey!</h1>
  </body>
</html>

All documents need this html wrapper, and then we have a head and body inside one level deep. Going deeper, we would maybe have titles, headings, text content and attributes such as an id. To visualise how this would look in the DOM tree, this example would look like this:

The DOM Tree
  • The document is the top of the tree. This is our web document or web page followed by the root html wrapper.
  • Below this, the head and body sections alongside each other. Our DOM is constructed of all these objects which mirror our HTML page.
  • One step further, adding a title element inside the head section, and a h1 element inside the body, and these are all nested or structured the same as our web page.

All these objects in the DOM are nodes. The h1 for example is an element node. Below the h1, and the title, we have a text node with the text content from each element.

Elements also have attributes such as href, class, and id, and these are attribute nodes.

JavaScript and the DOM

All of this happens in the background so why should we even care?

The DOM provides a way for JavaScript, or other languages, to connect to our HTML. It gives us access to this document tree so we can modify it. This means we can use JavaScript to create new HTML elements, remove them, change styling, attributes, and anything else which you will need.

Although we are writing JavaScript code, it uses the DOM to access the HTML elements, so they work together to allow us to do this.

We have already briefly looked at working with the DOM earlier when we changed the text we displayed in the browser, and we have a lot more to cover in this section, so let’s get started next by looking at ways to select elements.