29. Introduction to DOM
DOM (Document Object Model) is the tree-based representation of an HTML document created by the browser. The DOM allows JavaScript to access, manipulate, and modify the content, structure, and styling of a web page dynamically.
What Is the DOM?
When a browser opens an HTML file, it reads the HTML code and then builds a DOM tree — a hierarchical data structure that represents every element as a node.
<!DOCTYPE html>
<html>
<head>
<title>Skillversitas</title>
</head>
<body>
<h1>Portal Academic</h1>
<p>Welcome</p>
</body>
</html>
The browser converts this into a DOM tree:
Document
└── html
├── head
│ └── title
│ └── "Skillversitas"
└── body
├── h1
│ └── "Portal Academic"
└── p
└── "Welcome"
DOM vs HTML
| Aspect | HTML | DOM |
|---|---|---|
| What it is | Markup language | Object model (tree) |
| Where | Source code file | In the browser (memory) |
| Format | String/text | Nodes & objects |
| Modified by | Developer | JavaScript (at runtime) |
HTML is the source — the DOM is the active representation in the browser. When JavaScript modifies the DOM, the DOM changes but the original HTML stays the same (until the page is reloaded).
Code Example
DOM Tree Structure
// Access the root document
console.log(document); // Document node
console.log(document.documentElement); // <html> node
console.log(document.head); // <head> node
console.log(document.body); // <body> node
// Node types
console.log(document.nodeType); // 9 (Document)
console.log(document.body.nodeType); // 1 (Element)
console.log(document.body.firstChild.nodeType); // 3 (Text)
// Node names
console.log(document.nodeName); // "#document"
console.log(document.body.nodeName); // "BODY"
console.log(document.body.tagName); // "BODY"
DOM and Browser Rendering
// When the page loads, the browser does the following:
// 1. Fetch the HTML
// 2. Parse the HTML → build the DOM tree
// 3. Parse the CSS → build the CSSOM
// 4. Merge DOM + CSSOM → Render Tree
// 5. Layout → calculate the position of every element
// 6. Paint → draw pixels to the screen
// 7. Composite → merge all layers
// JavaScript can access the DOM once parsing is complete
// But it's better to wait for the DOMContentLoaded event:
// Too early — the element may not exist yet!
document.getElementById("data").textContent = "Hello";
// Wait for the DOM to be fully built
document.addEventListener("DOMContentLoaded", () => {
// The DOM is now ready
document.getElementById("data").textContent = "Hello";
});
// Or place the script at the end of body (already DOM-ready)
Reading the DOM Tree
// Traversal — walking the tree
const body = document.body;
// Parent
console.log(body.parentElement); // <html>
console.log(body.parentNode); // <html>
// Children
console.log(body.children); // HTMLCollection
console.log(body.childNodes); // NodeList (including text nodes)
console.log(body.firstChild); // first child node
console.log(body.lastChild); // last child node
console.log(body.firstElementChild); // first element child
// Siblings
console.log(body.nextElementSibling); // null (body is the last child of html)
console.log(body.previousElementSibling); // <head>
// Example of traversal to read data
const studentList = document.getElementById("studentList");
let current = studentList.firstElementChild;
while (current) {
console.log(current.textContent);
current = current.nextElementSibling;
}
DOM Specification & W3C
// The DOM is not part of JavaScript — the DOM is a separate API
// JavaScript accesses the DOM through interfaces defined by the W3C
// W3C DOM Levels:
// Level 1 (1998): Core DOM, HTML DOM
// Level 2 (2000): Events, Style, Traversal
// Level 3 (2004): Loading, Validation
// Modern: WHATWG DOM Standard (no longer the W3C)
// Example DOM interfaces:
// Document → representation of the document
// Element → every HTML element (div, p, h1, etc.)
// Text → text content within an element
// NodeList → collection of nodes
// HTMLCollection → collection of elements (live!)
DOM Ready States
// document.readyState changes as the page loads
console.log(document.readyState);
// "loading" — still parsing HTML
// "interactive" — DOM is ready, resources still loading
// "complete" — everything has finished
// Wait until the DOM is interactive or complete
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM siap!");
});
} else {
console.log("DOM is ready!");
}
// Or use defer in the script tag (recommended)
// <script src="app.js" defer></script>
// → runs automatically after the DOM has been parsed
Basic DOM Manipulation
// Once the DOM is ready, you can:
document.addEventListener("DOMContentLoaded", () => {
// Read content
const title = document.querySelector("h1");
console.log(title.textContent); // read text
console.log(title.innerHTML); // read HTML
console.log(title.getAttribute("id")); // read an attribute
// Change content
title.textContent = "Portal Academic v2";
title.style.color = "blue";
// Add a new element
const p = document.createElement("p");
p.textContent = "This is a new paragraph";
document.body.appendChild(p);
// Remove an element
title.remove();
// Clone an element
const clone = p.cloneNode(true); // true = deep clone
document.body.appendChild(clone);
});
DOM in a Campus Context
// How the browser renders an academic portal page:
// HTML from the server
// <div id="portal">
// <header>
// <h1>Technology University</h1>
// <nav>
// <a href="/dashboard">Dashboard</a>
// <a href="/grade">Grade</a>
// <a href="/schedule">Jadwal</a>
// </nav>
// </header>
// <main id="content">
// <h2>Welcome, Mike</h2>
// <div class="card">
// <p>GPA: 3.75</p>
// <p>Semester: 5</p>
// </div>
// </main>
// </div>
// The resulting DOM tree:
// Document
// └── html
// ├── head (meta, title, link, script)
// └── body
// └── div#portal
// ├── header
// │ ├── h1
// │ └── nav
// │ ├── a[href="/dashboard"]
// │ ├── a[href="/grade"]
// │ └── a[href="/schedule"]
// └── main#content
// ├── h2
// └── div.card
// ├── p
// └── p
// JavaScript can then manipulate this tree
Code Explanation
| Concept | Explanation |
|---|---|
| DOM | Tree representation of the HTML document in the browser |
| Nodes | Every element, text, and comment is a node in the tree |
document |
Root node, the entry point to the entire DOM |
DOMContentLoaded |
Event fired when the DOM is ready (before images/stylesheets load) |
load |
Event fired when EVERYTHING has finished (including images) |
defer |
A script attribute that runs JS after the DOM is ready |
Render Pipeline
HTML Parsing → DOM Tree
↓
CSS Parsing → CSSOM
↓
DOM + CSSOM = Render Tree
↓
Layout (calculate positions)
↓
Paint (draw)
↓
Composite (merge layers)
↓
SCREEN
Real-World Examples
An interactive academic portal page:
// app.js — placed with defer or at the end of body
document.addEventListener("DOMContentLoaded", () => {
// Read data from the DOM
const nameEl = document.querySelector("#name-student");
const ipkEl = document.querySelector("#gpa-student");
const courseListEl = document.querySelector("#course-list");
console.log(`Welcome, ${nameEl?.textContent ?? "Student"}`);
// Count the number of courses
const numCourses = courseListEl?.children?.length ?? 0;
console.log(`You are taking courses`);
// Add new info to the DOM
const infoCard = document.createElement("div");
infoCard.className = "info-card";
infoCard.innerHTML = `
<h3>Academic Summary</h3>
<p>Name: ${nameEl?.textContent}</p>
<p>GPA: ${ipkEl?.textContent}</p>
<p>Number of courses: ${numCourses}</p>
`;
const mainContent = document.querySelector("main");
mainContent?.prepend(infoCard);
console.log("Portal academicSystem siap!");
});
Example: DOM Validation with Safe Navigation
// Helper function for safe DOM access
function getDOMInfo(selector) {
const el = document.querySelector(selector);
if (!el) return { found: false, info: null };
return {
found: true,
info: {
tagName: el.tagName,
id: el.id || "(none)",
className: el.className || "(none)",
childCount: el.children.length,
textPreview: el.textContent?.slice(0, 50),
parentTag: el.parentElement?.tagName ?? "(root)"
}
};
}
// Usage
const header = getDOMInfo("header");
console.log(header);
// {
// found: true,
// info: {
// tagName: "HEADER",
// id: "(none)",
// className: "main-header",
// childCount: 2,
// textPreview: "Technology University Dashboard Grade Jadwal",
// parentTag: "DIV"
// }
// }
Conclusion
- The DOM is the tree representation of HTML built by the browser — JavaScript manipulates this tree, not the original HTML.
- DOMContentLoaded is the best event to start manipulating the DOM (before images/load finish).
- Nodes have relationships: parent, children, siblings — they can be traversed.
- DOM ≠ HTML: the DOM is active in browser memory; HTML is static in the file.
- Use the
deferattribute on script tags to ensure the DOM is ready before JavaScript runs.