Tutorials JavaScript DOM Introduction
Ch 40 / 78
Chapter 40 Beginner 8 min read JavaScript

DOM Introduction

The Document Object Model is the bridge between your HTML and JavaScript. When a browser loads a web page it builds a live, tree-shaped object representation of the document — and JavaScript can read, change, add, or remove any part of that tree in real time, making every interactive web page possible.

What you'll learn
What the DOM is and why it exists
How the browser turns HTML into a DOM tree
DOM node types — element, text, attribute, comment
The window and document global objects
Parent, child, and sibling relationships
DOM vs HTML — what's the same and what differs

What is the DOM?

The Document Object Model (DOM) is a programming interface created by the browser when it parses your HTML. It represents the page as a tree of JavaScript objects — one object per HTML element, text node, and comment — so that scripts can dynamically read and change the content, structure, and styling of the page.

The DOM is not your HTML source file — it is a live, in-memory representation. If your HTML has errors the browser may autocorrect them in the DOM. If JavaScript adds elements, the DOM grows, but your HTML file does not change.

Important distinction
HTML is a text file on disk — static markup. DOM is the live object tree the browser builds from that markup — dynamic and scriptable. "View Source" shows HTML; "Inspect Element" shows the DOM.

How the Browser Builds the DOM

When a browser receives an HTML document it goes through a multi-step rendering pipeline before anything appears on screen. The DOM is built early in this process:

HTML Bytes
Raw bytes from network
→
Tokenise
Tags, attrs, text
→
DOM Tree
Node objects in memory
→
CSSOM Tree
CSS rules parsed
→
Render Tree
DOM + CSSOM merged
→
Layout
Size & position
→
Paint
Pixels on screen
Tip
This is why you should place <script> tags at the bottom of the body (or use defer) — if a script runs before the DOM is fully built, elements it tries to access simply won't exist yet.

The DOM Tree

The DOM represents an HTML document as a hierarchical tree of nodes. Each HTML element becomes a node, text inside elements becomes text nodes, and attributes become attribute nodes. The window sits at the very top, with document as its property:

window └── document └── <html> ├── <head> │   ├── <meta charset="UTF-8"> │   └── <title> "My Page" </title> └── <body>      ├── <h1 id="title"> "Hello" </h1>      └── <ul class="list">          ├── <li> "Item 1" </li>          └── <li> "Item 2" </li>
window — global browser context object document — root of the DOM tree Element nodes — each HTML tag Attribute nodes — tag attributes Text nodes — text inside elements
HTML → DOM Tree
<!-- HTML source -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Page</title>
</head>
<body>
<h1 id="title">Hello World</h1>
<p>Welcome!</p>
</body>
</html>

// JavaScript can access any part of this tree
const h1 = document.getElementById("title");
console.log(h1.textContent); // "Hello World"
console.log(h1.tagName); // "H1"
console.log(h1.parentElement); // <body>
console.log(h1.nextElementSibling);// <p>

// Mutate it live — the page updates instantly
h1.textContent = "DOM is alive!";
h1.style.color = "#f7df1e";

DOM Node Types

Every item in the DOM tree is a Node. The DOM specification defines several node types, each with its own nodeType number. The four you'll encounter most often in practice are Element, Text, Attribute, and Comment nodes:

nodeType = 1
Element Node
Represents an HTML tag — the most common node type. Has child nodes, attributes, and CSS classes.
<div>, <p>, <h1>
nodeType = 2
Attribute Node
Represents an HTML attribute. In modern DOM APIs, attributes are accessed directly via element properties rather than as standalone nodes.
id="title", class="btn"
nodeType = 3
Text Node
Holds the actual text content inside an element, including whitespace and newlines between tags.
"Hello World"
nodeType = 8
Comment Node
Represents an HTML comment. They are included in the DOM tree and can be accessed by scripts.
<!-- comment -->
nodeType = 9
Document Node
The root of the entire DOM tree — the document object itself. Every other node is a descendant of this node.
document
nodeType = 10
DocumentType Node
Represents the doctype declaration at the top of an HTML document.
<!DOCTYPE html>
JavaScript — nodeType
// nodeType number tells you what kind of node it is
document.nodeType; // 9 — Document
document.documentElement.nodeType; // 1 — Element (<html>)
document.body.firstChild.nodeType; // 3 — Text (whitespace)

// Practical check — only process element nodes
document.body.childNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) { // 1
console.log(node.tagName);
}
});

// nodeName — readable name of the node
document.body.nodeName; // "BODY"
document.body.firstChild.nodeName; // "#text"

// nodeValue — text content of a text/comment node
const p = document.querySelector("p");
p.firstChild.nodeValue; // "Welcome!" (text node value)
p.nodeValue; // null (element nodes have no nodeValue)

window and document Objects

Two global objects are the entry points for all browser-side JavaScript. window is the global browser context and document is the root of the DOM tree:

window — browser global
window.document The DOM document object
window.location Current URL, navigate, reload
window.history Browser history — back, forward
window.navigator Browser & device info
window.innerWidth Viewport width in pixels
window.localStorage Persistent key-value storage
window.setTimeout Timer functions
window.alert Dialog boxes — alert, confirm, prompt
document — DOM root
document.documentElement The <html> element
document.head The <head> element
document.body The <body> element
document.title Page title — readable & writable
document.URL Current page URL string
document.querySelector Select elements by CSS selector
document.createElement Create a new element node
document.readyState "loading" | "interactive" | "complete"
JavaScript — window & document
// window is the global object — these are equivalent:
console.log(window.document === document); // true
console.log(window.alert === alert); // true

// Useful window properties
console.log(window.innerWidth); // viewport width in px
console.log(window.innerHeight); // viewport height in px
console.log(window.scrollY); // pixels scrolled vertically
console.log(window.location.href); // current URL

// document entry points
console.log(document.title); // page title
document.title = "New Title"; // changes the tab title live!

console.log(document.body); // <body> element
console.log(document.documentElement); // <html> element
console.log(document.readyState); // "complete" after load

// Wait for DOM to be ready before accessing elements
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM fully built — safe to query elements!");
const el = document.querySelector("h1");
console.log(el.textContent);
});

Navigating the Tree — Parent, Child & Sibling

Every node in the DOM tree knows its parent, children, and siblings. JavaScript gives you two sets of navigation properties — one that includes all nodes (text + comments), and one that only works with element nodes:

.parentNode / .parentElement
parentNode returns any node type parent. parentElement returns only element parents — returns null if the parent is not an element (e.g., for document.documentElement whose parent is the document node).
.childNodes / .children
childNodes is a live NodeList of all child nodes including text and comment nodes. children is a live HTMLCollection of only element children — usually what you want.
.firstChild / .firstElementChild
firstChild often returns a whitespace text node. firstElementChild skips text/comment nodes and returns the first actual element.
.nextSibling / .nextElementSibling
Moves to the next node or next element at the same level of the tree. Same distinction: nextSibling may return text nodes; nextElementSibling returns only elements.
JavaScript — Tree Navigation
// Given: <ul id="list"><li>One</li><li>Two</li><li>Three</li></ul>
const ul = document.getElementById("list");

// Parent navigation
ul.parentElement; // <body>
ul.parentElement.tagName; // "BODY"

// Children — prefer .children over .childNodes (avoids text nodes)
ul.children; // HTMLCollection [li, li, li]
ul.children.length; // 3
ul.children[0].textContent;// "One"

// First and last element child
ul.firstElementChild.textContent; // "One"
ul.lastElementChild.textContent; // "Three"

// Sibling navigation from the first <li>
const first = ul.firstElementChild;
first.nextElementSibling.textContent; // "Two"
first.previousElementSibling; // null — no sibling before first

// Walk all element children
Array.from(ul.children).forEach((li, i) => {
console.log(i, li.textContent); // 0 One | 1 Two | 2 Three
});

DOM vs HTML — Key Differences

The DOM is not a copy of your HTML. The browser can change the DOM compared to the source in several important ways:

Scenario HTML source DOM result
Missing required tags <table><tr><td>… without <tbody> Browser inserts <tbody> automatically in the DOM
Invalid nesting <p><div>text</div></p> Browser autocorrects — closes <p> before <div>
JS adds elements No <div id="new"> in file DOM has the element; "View Source" still doesn't
Case sensitivity <DIV> or <div> DOM always stores tag names in UPPERCASE
Whitespace Indentation spaces/newlines between tags Appear as text nodes in the DOM (nodeType 3)
HTML entities &amp; in HTML source Decoded to & in the DOM text node
⚡
Free Resource
Download our JavaScript DOM Cheat Sheet
DOM nodes, selectors, events & manipulation — all on one page.
Get Sheet

Try It — Live Editor

Experiment with the DOM below. The preview shows a live HTML page — JavaScript reads and modifies the DOM in real time.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the foundational DOM patterns you'll use in every real web project:

JavaScript — DOM Recipes
// ── Wait for DOM to be ready ─────────────────────────────────
document.addEventListener("DOMContentLoaded", () => {
// Safe to query and manipulate DOM here
});

// ── Read element content and attributes ───────────────────────
const el = document.querySelector("#hero");
el.textContent; // plain text inside
el.innerHTML; // HTML string inside
el.id; // "hero"
el.className; // space-separated class string
el.getAttribute("data-id"); // custom attribute

// ── Check if element exists before using it ──────────────────
const btn = document.querySelector("#submit");
if (btn) btn.addEventListener("click", handler);

// ── Walk a NodeList safely ────────────────────────────────────
const items = document.querySelectorAll(".item");
items.forEach(item => console.log(item.textContent));
// Or spread to array for full array methods:
[...items].filter(i => i.classList.contains("active"));

// ── Create, build, and insert a new element ──────────────────
const card = document.createElement("div");
card.className = "card";
card.innerHTML = `<h3>Title</h3><p>Body text</p>`;
document.body.appendChild(card);

// ── Remove an element ────────────────────────────────────────
const old = document.querySelector(".outdated");
old?.remove(); // optional chaining — safe if not found

// ── Change document title dynamically ────────────────────────
document.title = `(${unreadCount}) Inbox — MyApp`;
Quick Check
What is the nodeType number of an HTML element node (e.g. <div>)?
Quick Check
Which property gives you only the element children of a node, excluding text and comment nodes?
Chapter Summary
  • The DOM (Document Object Model) is a live, tree-shaped JavaScript object the browser builds from HTML — it is not the HTML file itself.
  • The browser parses HTML → builds the DOM tree → combines with CSSOM → lays out → paints pixels. JavaScript can modify the DOM at any point after it is built.
  • Every item in the DOM is a Node with a nodeType: Element (1), Text (3), Comment (8), Document (9).
  • window is the global browser context; document is the root of the DOM tree and the main entry point for querying elements.
  • Use .children, .firstElementChild, and .nextElementSibling to navigate element nodes only, avoiding whitespace text nodes.
  • Always wait for the DOM to be ready with DOMContentLoaded or place scripts at the end of <body> / use defer.
  • The DOM can differ from the HTML source — browsers autocorrect invalid markup, add missing elements like <tbody>, and JavaScript can add/remove nodes dynamically.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel