Computer Programming 1 (JavaScript) • Web Basics (DOM & Events)

Understanding the DOM — I can explain the DOM as a structured representation of a webpage at a conceptual level.

Discover how browsers transform HTML code into a living, interactive tree structure you can manipulate with JavaScript.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

In the earliest days of the web, pages were completely static. You wrote some HTML, uploaded it to a server, and users could read it — but that was about it. There was no way to click a button and watch content change, no dropdown menus that appeared on hover, and no interactive forms that responded as you typed. Every single change to a page required loading an entirely new HTML file from the server.

As the web grew in the mid-1990s, developers and users alike wanted pages that could respond to actions without reloading. This meant the browser needed a way to let programming languages like JavaScript reach into a webpage and change its content, structure, or style on the fly. The solution was the Document Object Model, or DOM — a standardized way for programs to represent and interact with the elements of a webpage.

1991 • HTML Is Born

Tim Berners-Lee creates HTML as a simple markup language for sharing documents. Pages are entirely static with no interactivity.

1995 • JavaScript Arrives

Brendan Eich creates JavaScript at Netscape in just 10 days. For the first time, browsers can run scripts that manipulate page content — but each browser does it differently.

1998 • W3C Standardizes DOM Level 1

The World Wide Web Consortium (W3C) publishes the first official DOM specification, creating a universal standard so the same JavaScript code works across all browsers.

2004–2009 • The Ajax Revolution

Technologies like Ajax allow pages to fetch data from servers and update the DOM without a full page reload. Gmail and Google Maps demonstrate the power of dynamic DOM manipulation.

2010s–Now • Modern Frameworks

React, Vue, and Angular build sophisticated user interfaces by managing the DOM automatically. Understanding the DOM remains essential because these tools are built on top of it.

The central question the DOM answers is straightforward: how can a programming language understand the structure of a webpage well enough to read, change, add, or remove any part of it? Without the DOM, JavaScript would have no way to know what elements exist on the page or how they relate to each other.

SECTION 2

Core Principles & Definitions

At its core, the DOM is a model — a structured representation that the browser builds every time it loads a webpage. When you write HTML, you are writing a set of instructions. The browser reads those instructions and constructs the DOM, which is the actual in-memory object that the browser uses to render the page on screen and that JavaScript uses to interact with it.

1

Tree Structure

The DOM organizes every element on a webpage into a tree — a hierarchy where each element is a node connected to a parent, and potentially to children. The topmost node is the document object itself.
2

Nodes Everywhere

Everything in the DOM is a node: HTML tags become element nodes, the text inside them becomes text nodes, and HTML attributes become attribute nodes.
3

Parent–Child Relationships

Nesting in HTML creates parent–child relationships in the DOM. An element inside another element is that element's child. Elements at the same level are called siblings.
4

Live & Dynamic

The DOM is live. When JavaScript changes a node — say, updating text or adding a new element — the browser immediately re-renders that part of the page. You do not need to reload.
5

Language-Neutral API

The DOM is technically language-neutral: the W3C specification can be implemented by any programming language. In web browsers, JavaScript is the language that accesses the DOM through built-in methods like document.getElementById().
✦

KEY TAKEAWAY

Think of the DOM like a family tree for a webpage. The document is the great-grandparent at the top. The <html> element is its child, which has two children of its own: <head> and <body>. Every heading, paragraph, image, and link is a member of this family tree, and you can find any "relative" by tracing the branches. JavaScript is like a messenger that can walk up and down this family tree to deliver changes to any member.

SECTION 3

The DOM Tree — Visual Explanation

The diagram below shows how a simple HTML document is translated into a DOM tree. On the left you can imagine the raw HTML code; the diagram represents the tree structure the browser builds in memory. Each box is a node, and the lines connecting them represent parent–child relationships.

DOM Tree for a Simple Webpagedocument<html><head><body><title>"My Page"<h1>"Hello World"<p>"Welcome!"<img>LEGENDDocument rootRoot elementStructural nodesContent nodesText
This tree represents the DOM for a simple webpage containing a title, a heading, a paragraph, and an image. The document node sits at the top, with <html> as its only child. Solid lines show parent–child relationships between element nodes, while dashed lines connect element nodes to their text content.

Notice how the tree mirrors the nesting of your HTML. The <h1>, <p>, and <img> elements are all children of <body>, which means they are siblings of each other. The text inside an element — like "Hello World" inside <h1> — is stored as a separate text node that is a child of the element node. This distinction between element nodes and text nodes is a key concept that helps you understand what you are actually selecting and modifying when you write JavaScript.

SECTION 4

How the Browser Builds the DOM

Understanding the DOM at a conceptual level means knowing what happens between the moment your browser receives raw HTML and the moment pixels appear on screen. The browser follows a predictable pipeline to turn your code into a visual, interactive page. Let's walk through the key stages of this process.

The Rendering Pipeline

First, the browser's HTML parser reads the raw HTML text character by character. As it encounters opening tags like <div>, it creates a new element node in the DOM tree. When it finds text between tags, it creates a text node. When it encounters a closing tag like </div>, it knows the current element is complete and moves back up to the parent. This process is sometimes called parsing.

Second, the browser builds the CSSOM (CSS Object Model) — a similar tree structure for all the styles that apply to the page. The browser then combines the DOM and CSSOM into a render tree that determines what is visible and how it looks. Finally, the browser paints the pixels onto your screen based on the render tree.

How the Browser Builds & Uses the DOMHTML Code<html>...</html>ParserReads each tagDOM TreeIn-memoryrepresentationRender TreeDOM + CSSOMScreenPixels!CSS Stylescolor: red;CSSOMStyle treeJavaScriptModifies DOMJavaScript can modify the DOM at any time, triggering the browser to re-render.
The browser pipeline: HTML is parsed into the DOM, CSS is parsed into the CSSOM, both combine into the render tree, and pixels appear on screen. JavaScript can modify the DOM at any point, which triggers re-rendering.

The critical insight here is that the DOM is not the HTML itself. Your HTML file is the blueprint, but the DOM is the actual building the browser constructs from that blueprint. When JavaScript modifies the DOM — adding a new paragraph, changing a color, or removing a button — it is changing the building, not rewriting the blueprint. The original HTML file on the server remains unchanged.

SECTION 5

Types of DOM Nodes

Not every node in the DOM tree is the same. Understanding the different types of nodes helps you know exactly what you are working with when you interact with the DOM through JavaScript. While the DOM specification defines twelve node types, you will primarily work with three of them as a beginning developer.

Node TypeDescriptionExamplenodeType Value
Element NodeRepresents an HTML tag. This is the most common node type you will interact with.<div>, <p>, <h1>1
Text NodeContains the actual text content inside an element. Even whitespace between tags can create text nodes."Hello World" inside a <p>3
Comment NodeRepresents HTML comments. These exist in the DOM but are not rendered on screen.<!-- TODO -->8
Document NodeThe root node of the entire DOM tree. Accessed in JavaScript via the global document object.document9
Attribute NodeRepresents an attribute of an element (like class or id). In modern DOM usage, these are typically accessed as properties of element nodes.class="main", id="nav"2

The five most common DOM node types

A common misconception is that the DOM only contains the HTML tags you write. In reality, text nodes are separate objects from the elements that contain them. When you write <p>Hello</p>, the DOM actually creates two nodes: one element node for <p> and one text node for "Hello" that is a child of the <p> element node. This is why methods like .textContent exist — they reach into the element and access the text node within.

💡

Common Surprise

Whitespace in your HTML — the spaces and line breaks you use to keep your code readable — can create invisible text nodes in the DOM. For example, a line break between </h1> and <p> creates a text node containing just a newline character. This is why sometimes iterating through child nodes gives you unexpected results!

SECTION 6

Worked Example: Tracing HTML to DOM

Let's work through a concrete example. Given the following HTML, we will trace exactly how the browser builds the DOM tree and identify each node, its type, and its relationships.

ℹ

Source HTML

<html> <head> <title>Blog</title> </head> <body> <h1>My Blog</h1> <p class="intro">Welcome to <strong>my</strong> blog.</p> </body> </html>

Tracing the DOM Tree

  1. 1

    Step 1 — Identify the Root

    The browser creates the document node as the root of the tree. This is always the starting point and exists before any HTML is even parsed.
    Root: document (nodeType 9)
  2. 2

    Step 2 — Parse the <html> Tag

    The parser encounters <html> and creates an element node as the child of document. This is called the document element or root element.
    document → html
  3. 3

    Step 3 — Build the <head> Branch

    Inside <html>, the parser finds <head> and creates it as a child. Then it finds <title> (child of head) and the text "Blog" (a text node, child of title).
    html → head → title → "Blog"
  4. 4

    Step 4 — Build the <body> Branch

    The <body> element becomes the second child of <html> (a sibling of head). Inside body, the parser creates an <h1> element with a text node "My Blog".
    html → body → h1 → "My Blog"
  5. 5

    Step 5 — Parse the Nested <p> Element

    The <p class="intro"> element is created as a child of body, with the attribute class="intro". Notice that the paragraph contains mixed content: the text "Welcome to ", then a <strong> element containing the text "my", then another text node " blog.". The <p> element ends up with three children: a text node, an element node, and another text node.
    p has 3 children: "Welcome to " → <strong> → " blog."
  6. 6

    Step 6 — Count the Nodes

    Let's count every node in our tree. We have the document node, plus element nodes for html, head, title, body, h1, p, and strong (that's 8 element nodes). We have text nodes for "Blog", "My Blog", "Welcome to ", "my", and " blog." (that's 5 text nodes). In total, that's 1 document node + 8 element nodes + 5 text nodes.
    Total: 14 nodes (1 document + 8 elements + 5 text)

SECTION 7

DOM vs. HTML — Key Differences

One of the most important things to understand is that the DOM and the HTML source code are related but not identical. The browser can actually modify the DOM during parsing to fix errors in your HTML, and JavaScript can further modify the DOM after the page loads. Here are the key differences.

FeatureHTML SourceDOM
What it isA text file with markup tagsAn in-memory object (tree of nodes)
Where it livesOn the server or your hard driveIn the browser's memory (RAM)
Can it change?Only if you edit the fileYes — JavaScript changes it live
Error handlingCan contain errors (e.g., missing closing tags)The browser auto-corrects errors during parsing
JavaScript accessJavaScript cannot directly read the .html fileJavaScript reads and writes through the DOM API
View Source vs. Inspect"View Page Source" shows the original HTML"Inspect Element" (DevTools) shows the live DOM

How HTML source code differs from the DOM

✦

KEY TAKEAWAY

Think of HTML as the recipe and the DOM as the actual dish you cooked from that recipe. The recipe (HTML) stays in the cookbook unchanged, but you can add extra salt or garnish to the actual dish (the DOM) at any time. If you look at the recipe, it still says the original ingredients. But if you taste the dish, you get whatever changes were made. Similarly, "View Page Source" shows the recipe, while "Inspect Element" in DevTools shows the current state of the dish.

SECTION 8

Connecting to Advanced Concepts

Understanding the DOM as a tree structure is the foundation for everything you will do in interactive web development. Once you are comfortable with the concept, you will begin using JavaScript methods to navigate and modify this tree — a practice known as DOM manipulation. Beyond that, you will learn about events that let you respond to user actions like clicks and keystrokes.

ConceptWhat You Know NowWhat Comes Next
DOM StructureThe DOM is a tree of nodes representing a webpageUsing methods like querySelector() and getElementById() to select specific nodes
Node TypesElements, text nodes, attributes, and the document nodeTraversing the tree with properties like .parentNode, .children, and .nextSibling
Live UpdatesJavaScript changes the DOM and the page re-rendersCreating and removing elements dynamically with createElement() and removeChild()
User InteractionPages can be interactiveEvent listeners like addEventListener('click', ...) that trigger DOM changes when users interact
FrameworksThe DOM is how browsers represent pagesLibraries like React use a "virtual DOM" to manage updates more efficiently at scale

From conceptual understanding to practical skills

Everything in modern web development — from simple form validation to complex single-page applications — relies on the DOM. The conceptual understanding you are building right now is not a stepping stone you will leave behind; it is the mental model you will use every time you write JavaScript that interacts with a webpage. When something goes wrong with your code, being able to picture the DOM tree in your mind and reason about parent–child relationships will help you debug faster and write cleaner code.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain the difference between an HTML file and the DOM. Why are they not the same thing?
Show answer
An HTML file is a static text document stored on a server or hard drive. It contains the markup code that describes the page's structure. The DOM, on the other hand, is a live, in-memory tree structure that the browser creates by parsing the HTML file. They differ in three key ways: (1) the browser may auto-correct errors in HTML when building the DOM, so the DOM might contain elements like <tbody> that you never wrote; (2) JavaScript can modify the DOM after it is built, but the original HTML file remains unchanged; (3) the HTML file is plain text, while the DOM is a collection of programmable objects in the browser's memory.

Question 2: BASIC CALCULATION

Given this HTML snippet, count the total number of element nodes and text nodes in the resulting DOM tree: <ul> <li>Apples</li> <li>Bananas</li> </ul>
Show answer
Element nodes: <ul> (1), two <li> elements (2) = 3 element nodes. Text nodes: "Apples" inside the first <li> (1), "Bananas" inside the second <li> (1) = 2 text nodes. Note: there may also be whitespace text nodes between the tags (due to line breaks and indentation), but when counting visible content nodes, the answer is 3 element nodes + 2 text nodes = 5 content nodes. If you count whitespace text nodes (between <ul> and the first <li>, between the two <li> elements, and after the last <li>), you would add 3 more, for a total of 8 nodes.

Question 3: INTERMEDIATE

Consider the following HTML: <div id="container"> <h2>Title</h2> <p>Hello <em>world</em>!</p> </div> Identify the parent, children, and siblings of the <p> element. Also, list all children of the <p> element itself, specifying each child's node type.
Show answer
The <p> element's parent is the <div id="container"> element. Its sibling is the <h2> element (they are both children of the same parent). The <p> element has three children: (1) a text node containing "Hello ", (2) an element node <em> which itself contains a text node "world", and (3) a text node containing "!". This demonstrates that when an element has both plain text and nested elements, the text is split into separate text nodes around the nested element.

Question 4: APPLIED

You open a webpage and use the browser's DevTools (Inspect Element) to examine a button. The DevTools show: <button class="btn-primary" disabled>Submit</button>. However, when you view the page source, the button reads <button class="btn-secondary">Submit</button>. Explain why the two look different, and which one represents the current state of the page.
Show answer
The two views differ because "View Page Source" shows the original HTML file as it was downloaded from the server, while DevTools shows the live DOM — the current state of the page in the browser's memory. Something changed the DOM after it was initially built: JavaScript must have run after the page loaded and (1) changed the class attribute from "btn-secondary" to "btn-primary", and (2) added the "disabled" attribute to the button. The DevTools view represents the current, actual state of the page — what the user is seeing and interacting with right now. The original HTML source is historical information about what was initially loaded.

Question 5: CRITICAL THINKING

A developer writes HTML with an <img> tag nested inside a <p> element, and a <table> without any <tbody> element. When they inspect the DOM in DevTools, they see a <tbody> that they never wrote. Why does this happen, and what does it reveal about the relationship between HTML and the DOM?
Show answer
This happens because the DOM is not a direct copy of the HTML — it is the result of the browser's parsing and error-correction process. The HTML specification requires that table rows (<tr>) be wrapped in a <tbody> element (or <thead>/<tfoot>). When the parser encounters a <tr> directly inside a <table> without a <tbody>, it automatically inserts one to create a valid DOM. This reveals a critical truth: the DOM is the browser's interpretation and correction of your HTML, not a mirror of it. You should always use DevTools (not View Source) when debugging, because the DOM is what actually drives the page rendering.

SUMMARY

Summary

Summary

The Document Object Model (DOM) is the browser's in-memory tree structure that represents every element, text string, and attribute of a webpage as a node. It is built by the browser's HTML parser and organized through parent–child relationships that mirror the nesting of your HTML tags. The main node types you work with are element nodes (HTML tags), text nodes (content within tags), and the document node (the root of the tree).

A crucial concept is that the DOM is not the same as the HTML source. The browser may correct errors during parsing, and JavaScript can modify the DOM dynamically without changing the original HTML file. This is what makes modern web pages interactive. You can observe the live DOM using your browser's DevTools (Inspect Element), while "View Page Source" shows the original HTML. Understanding the DOM as a structured, live representation of a webpage is the essential foundation for DOM manipulation, event handling, and building interactive web applications.

Varsity Tutors • Computer Programming 1 (JavaScript) • Understanding the DOM