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 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.
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:
<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 — 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 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:
document object
itself. Every other node is a descendant of this node.// 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 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 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 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 often returns a whitespace text node.
firstElementChild skips text/comment nodes and returns the first actual
element.
nextSibling may return text nodes;
nextElementSibling returns only elements.
// 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 | & in HTML source |
Decoded to & in the DOM text node |
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.
Common Patterns & Recipes
These are the foundational DOM patterns you'll use in every real web project:
// ── 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`;nodeType number of an HTML element node (e.g.
<div>)?
- 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). windowis the global browser context;documentis the root of the DOM tree and the main entry point for querying elements.- Use
.children,.firstElementChild, and.nextElementSiblingto navigate element nodes only, avoiding whitespace text nodes. - Always wait for the DOM to be ready with
DOMContentLoadedor place scripts at the end of<body>/ usedefer. - 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.