Skip to main content

🌳 Lesson 13: Introduction to the DOM

The DOM is the bridge between your HTML and JavaScript. It turns a static web page into a living, interactive experience you can read, change, and control with code.

🎯 Learning Objectives

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

  • Explain what the DOM is and why it matters
  • Describe how the browser builds the document tree from HTML
  • Identify key DOM objects: document, window, elements, and nodes
  • Navigate the DOM tree using parent, child, and sibling properties
  • Use the DevTools Elements panel to inspect and explore the DOM
  • Understand the difference between HTML source and the live DOM

Estimated Time: 45 minutes

Project: Explore the DOM tree using the console and DevTools

📑 In This Lesson

What Is the DOM?

The DOM (Document Object Model) is a programming interface for web pages. When a browser loads HTML, it doesn't just display text — it builds an in-memory representation of the page as a tree of objects. This tree is the DOM.

JavaScript can't read or modify HTML files directly. Instead, it interacts with the DOM — adding, removing, and changing elements, text, styles, and attributes. Every interactive feature on a web page works through the DOM.

graph TD A["HTML Source Code"] -->|"Browser parses"| B["DOM Tree
(in memory)"] B -->|"Browser renders"| C["What You See
(on screen)"] D["JavaScript"] -->|"Reads & modifies"| B B -->|"Changes trigger"| C style A fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#1e293b style B fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style C fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style D fill:#fce7f3,stroke:#ec4899,stroke-width:2px,color:#1e293b

Think of it this way: HTML is the blueprint, the DOM is the building, and JavaScript is the contractor who can remodel the building after it's constructed.

The Document Tree

The DOM is structured as a tree, just like a family tree. Every piece of the page — elements, text, attributes — is a node in this tree.

Consider this simple HTML:


<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Hello!</h1>
    <p>Welcome to my <strong>awesome</strong> page.</p>
  </body>
</html>
                

The browser turns this into the following tree:

graph TD DOC["document"] --> HTML["html"] HTML --> HEAD["head"] HTML --> BODY["body"] HEAD --> TITLE["title"] TITLE --> T1["'My Page'"] BODY --> H1["h1"] BODY --> P["p"] H1 --> T2["'Hello!'"] P --> T3["'Welcome to my '"] P --> STRONG["strong"] P --> T4["' page.'"] STRONG --> T5["'awesome'"] style DOC fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#1e293b style HTML fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style HEAD fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style BODY fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style TITLE fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style H1 fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style P fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style STRONG fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style T1 fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style T2 fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style T3 fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style T4 fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style T5 fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b

Key relationships in this tree:

  • Parent: <html> is the parent of <head> and <body>
  • Children: <h1> and <p> are children of <body>
  • Siblings: <h1> and <p> are siblings (same parent)
  • Text nodes: "Hello!" is a text node inside <h1>

Key DOM Objects

window — The Global Object

window represents the browser window. It's the top-level object — everything lives inside it, including the DOM.


// window properties you already know
console.log(window.innerWidth);   // Browser width in pixels
console.log(window.innerHeight);  // Browser height in pixels
console.log(window.location.href);  // Current URL

// You've been using window methods all along
window.console.log("Hello!");     // Same as console.log()
window.alert("Hi!");              // Same as alert()
window.setTimeout(() => {}, 1000); // Same as setTimeout()
                

document — The Page Itself

document is the entry point to the DOM. It represents the entire HTML document and provides methods to find and create elements.


// document basics
console.log(document.title);           // Page title
console.log(document.URL);             // Page URL
console.log(document.documentElement); // The <html> element
console.log(document.head);            // The <head> element
console.log(document.body);            // The <body> element

// These are the methods you'll use most (covered in the next lesson)
// document.querySelector()
// document.querySelectorAll()
// document.getElementById()
// document.createElement()
                

Elements — The Building Blocks


// Every HTML tag becomes an element object in the DOM
const heading = document.querySelector("h1");

// Elements have properties you can read and change
console.log(heading.tagName);       // "H1"
console.log(heading.textContent);   // The text inside the element
console.log(heading.className);     // CSS classes
console.log(heading.id);            // The id attribute
console.log(heading.style);         // Inline styles object
                

Node Types

Not everything in the DOM tree is an HTML element. The DOM has different node types.

Node Type nodeType Value Example Description
Element1<div>, <p>, <h1>HTML tags
Text3"Hello World"Text content inside elements
Comment8<!-- note -->HTML comments
Document9documentThe root document itself

// Check a node's type
const heading = document.querySelector("h1");
console.log(heading.nodeType);   // 1 (Element)
console.log(heading.nodeName);   // "H1"

const textNode = heading.firstChild;
console.log(textNode.nodeType);  // 3 (Text)
console.log(textNode.nodeName);  // "#text"
                

💡 Elements vs. Nodes

In practice, you'll mostly work with elements (node type 1). Text nodes and comment nodes exist in the tree, but you'll rarely need to interact with them directly. Methods like querySelector return elements, not raw nodes.

Traversing the Tree

Once you have a reference to an element, you can navigate to its relatives — parent, children, and siblings.

Parent


const item = document.querySelector("li");
const list = item.parentElement;    // The <ul> or <ol> containing this <li>
const body = list.parentElement;    // Keeps going up the tree
                

Children


const list = document.querySelector("ul");

// All child elements (ignores text nodes)
console.log(list.children);            // HTMLCollection of <li> elements
console.log(list.children.length);     // Number of child elements
console.log(list.children[0]);         // First <li>

// First and last child elements
console.log(list.firstElementChild);   // First <li>
console.log(list.lastElementChild);    // Last <li>
                

Siblings


const second = list.children[1];

console.log(second.previousElementSibling);  // The <li> before this one
console.log(second.nextElementSibling);      // The <li> after this one
                
graph TD UL["ul
(parentElement)"] --> LI1["li
(firstElementChild)"] UL --> LI2["li
(children[1])"] UL --> LI3["li
(lastElementChild)"] LI1 -->|"nextElementSibling"| LI2 LI2 -->|"nextElementSibling"| LI3 LI3 -->|"previousElementSibling"| LI2 LI2 -->|"previousElementSibling"| LI1 style UL fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#1e293b style LI1 fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style LI2 fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b style LI3 fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#1e293b

⚠️ Element vs. Node Properties

There are two sets of traversal properties. The Element versions (recommended) skip text nodes and comments. The Node versions include everything.

Element Properties (Use These) Node Properties (Include Text Nodes)
parentElementparentNode
childrenchildNodes
firstElementChildfirstChild
lastElementChildlastChild
nextElementSiblingnextSibling
previousElementSiblingpreviousSibling

Exploring with DevTools

The browser's DevTools are your best friend for understanding the DOM. Here's how to use them.

Opening DevTools

  • Windows/Linux: F12 or Ctrl + Shift + I
  • Mac: Cmd + Option + I
  • Right-click: "Inspect" on any element

The Elements Panel

The Elements panel shows the live DOM tree. You can:

  • Hover over elements to highlight them on the page
  • Click to expand/collapse sections of the tree
  • Double-click to edit text or attributes in real time
  • Delete elements to see what happens
  • Drag elements to rearrange them

The Console + DOM


// Try these in your browser console right now!

// Select this page's heading
document.querySelector("h1");

// Change the heading text
document.querySelector("h1").textContent = "I changed this!";

// Change the background color
document.body.style.backgroundColor = "lightyellow";

// Count how many sections are on this page
document.querySelectorAll("section").length;

// $0 — refers to the currently selected element in Elements panel
// After clicking an element in the Elements panel:
// $0.tagName
// $0.textContent
// $0.children
                

✅ Pro Tip: The $0 Shortcut

In DevTools, click any element in the Elements panel. Then switch to the Console and type $0 — it refers to the element you just selected. This is incredibly useful for quick experiments. $1 refers to the previously selected element.

HTML Source vs. Live DOM

An important distinction: the HTML source code and the DOM are not the same thing. The DOM is a living, mutable representation that starts from HTML but can diverge.


// The DOM can contain things that aren't in the HTML source:

// 1. Browser corrections — browsers fix invalid HTML
// Missing <tbody> in tables? The browser adds it to the DOM.

// 2. JavaScript additions — code can create new elements
const newParagraph = document.createElement("p");
newParagraph.textContent = "I was created by JavaScript!";
document.body.appendChild(newParagraph);
// This <p> exists in the DOM but not in the HTML file

// 3. User interactions — form inputs change the DOM
// When a user types in an <input>, the DOM's .value updates
// but the HTML source attribute stays the same
                

💡 View Source vs. Inspect

  • View Source (Ctrl/Cmd + U): Shows the original HTML file from the server — static, never changes.
  • Inspect / Elements Panel: Shows the live DOM — reflects JavaScript changes, browser corrections, and user interactions.

Hands-on Exercise

🏋️ Exercise: DOM Explorer

Objective: Use the browser console to explore this very page's DOM. Open DevTools (F12) and try each task in the Console.


// Do these in your browser console on THIS page:

// 1. Find the page title
document.title

// 2. Get the main heading
document.querySelector("h1")

// 3. How many sections does this lesson have?
document.querySelectorAll(".lesson-section").length

// 4. Get the breadcrumb navigation
document.querySelector(".breadcrumb")

// 5. Navigate the tree manually:
//    Start from the body, get its first element child,
//    then that element's next sibling, and so on
document.body.firstElementChild
document.body.firstElementChild.nextElementSibling

// 6. Change the page heading text
document.querySelector("h1").textContent = "🌳 I Explored the DOM!"

// 7. Change the page background color
document.body.style.backgroundColor = "#f0f9ff"

// 8. Find all links on the page and count them
document.querySelectorAll("a").length

// 9. Use the Elements panel:
//    - Click on different elements and watch them highlight
//    - Try $0 in the console after selecting an element
//    - Double-click text in the Elements panel to edit it
//    - Try deleting an element (select it, press Delete key)

// 10. Bonus: Walk the full tree from document to a deep element
document.documentElement  // <html>
    .children[1]          // <body>
    .children[3]          // <main>
    .firstElementChild    // .container
    .firstElementChild    // <header>
    .firstElementChild    // <h1>
                    
💡 Hint

All of these tasks are done in the browser console, not in a code file. Open DevTools with F12 or Ctrl + Shift + I, click the Console tab, and type each line. Refresh the page to undo your changes.

🎯 Quick Quiz

Question 1: What is the DOM?

Question 2: Which object is the entry point to the DOM?

Question 3: What does element.parentElement return?

Summary

🎉 Key Takeaways

  • The DOM is the browser's in-memory tree representation of your HTML page
  • document is your entry point — it provides methods to find and create elements
  • The DOM tree has parents, children, and siblings — navigate with properties like parentElement, children, nextElementSibling
  • Use Element properties (not Node properties) to skip text nodes when traversing
  • The DevTools Elements panel shows the live DOM, not the original HTML source
  • JavaScript changes the DOM, which the browser re-renders — the HTML file stays unchanged
  • The $0 console shortcut references the currently selected element in DevTools

📚 Additional Resources

🚀 What's Next?

Now that you understand what the DOM is, the next lesson teaches you to select and modify elements — changing text, classes, styles, and attributes with JavaScript. This is where things get hands-on.