The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page as a structured tree of nodes, allowing JavaScript to dynamically access, modify, add, or delete elements, attributes, and styles.
flowchart TD
Doc["document (Root Node)"] --> RootEl["<html> (Root Element)"]
RootEl --> Head["<head>"]
RootEl --> Body["<body>"]
Head --> Title["<title> Text Node"]
Body --> HeaderNode["<header> Node"]
Body --> MainNode["<main> Node"]
MainNode --> Paragraph["<p> Element Node"]
Paragraph --> TextContent["'Hello DOM' Text Node"]
| Node Type Constant | Interface | Description |
|---|---|---|
Node.ELEMENT_NODE (1) |
Element |
HTML element tags (<div>, <p>, <button>). |
Node.ATTRIBUTE_NODE (2) |
Attr |
Element attributes (id, class, src). |
Node.TEXT_NODE (3) |
Text |
Character text content inside elements. |
Node.COMMENT_NODE (8) |
Comment |
HTML comment blocks (<!-- ... -->). |
Node.DOCUMENT_NODE (9) |
Document |
Entire document root (window.document). |
// Demonstrating DOM Inspection and Node vs Element Distinctions
document.addEventListener("DOMContentLoaded", () => {
// 1. Inspecting Root Document
console.log(`Document Title: ${document.title}`);
console.log(`Root Element: ${document.documentElement.nodeName}`); // "HTML"
console.log(`Body Node Type: ${document.body.nodeType}`); // 1 (ELEMENT_NODE)
// 2. Demonstrating Nodes vs Elements
const container = document.createElement("div");
container.innerHTML = " <p>First Paragraph</p> ";
console.log(`childNodes count (Includes whitespace Text Nodes): ${container.childNodes.length}`); // 3
console.log(`children count (Element Nodes ONLY): ${container.children.length}`); // 1
});
childNodes vs children: childNodes returns all node types (including line break whitespace Text Nodes). Use children when you only want HTML element tags.DOMContentLoaded event handlers or using script defer.What is the difference between element.nodeType === 1 and element.nodeType === 3?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.