Lesson 1: The Document Object Model (DOM)

Learning Objectives

By the end of this lesson, learners will be able to:

  • Understand what the DOM is and why it’s important in web development
  • Visualize how HTML elements are structured in the DOM tree
  • Recognize how JavaScript interacts with the DOM
  • Understand that the DOM allows dynamic content and style changes
  • Access the DOM using the document object

What Is the DOM?

The DOM (Document Object Model) is a programmatic representation of a webpage. It turns HTML into a tree-like structure that JavaScript can access, modify, and interact with.

When a browser loads a webpage:

  1. It reads the HTML.
  2. It builds the DOM — a live, up-to-date model of the page.
  3. JavaScript uses this model to select, update, create, or delete elements on the page.

Think of the DOM as a digital map of your HTML, where each element is a node you can find, change, or remove with JavaScript.


Visual Representation

Given this HTML:

<html>
  <body>
    <h1>Hello, world!</h1>
    <p>This is a paragraph.</p>
  </body>
</html>

The DOM structure (tree) looks like:

document
 └── html
     └── body
         ├── h1 → "Hello, world!"
         └── p → "This is a paragraph."

Each HTML tag becomes a node in the tree, and content inside the tag is a text node.


Why Is the DOM Important?

The DOM allows JavaScript to:

  • Access HTML elements (like buttons, inputs, headings)
  • Change content on the page dynamically
  • Respond to user actions (clicks, typing, etc.)
  • Add or remove content and styles in real time

Without the DOM, a webpage would be static and unresponsive.


Accessing the DOM in JavaScript

JavaScript accesses the DOM through the document object, which represents the entire HTML document.

console.log(document);

This prints out the full HTML structure in the browser console.

You can use document to:

  • Select elements (getElementById, querySelector, etc.)
  • Read and change text
  • Modify styles
  • Add/remove elements

Example: Change the Text of a Paragraph

HTML:

<p id="message">Welcome!</p>

JavaScript:

document.getElementById("message").textContent = "Hello from JavaScript!";

✅ This uses the DOM to find the paragraph and change its content — without reloading the page!


DOM Terminology

TermDescription
NodeAny item in the DOM tree (element, text, attribute, etc.)
ElementAn HTML tag like <p>, <div>, <button>, etc.
Text NodeThe text inside an element
Root NodeThe top-level node (document)
Parent/ChildElements that contain or are contained by others