The DOM — Document Object Model

📚 Lesson 14 of 40  •  ⏱ 10 min read  •  Intermediate

What is the DOM?

When a browser loads an HTML page, it creates a tree-like structure called the Document Object Model (DOM). JavaScript can read and modify this tree to change what users see.

Think of it this way: HTML is the blueprint, the DOM is the living building, and JavaScript is what can renovate the building while people are inside.

DOM Tree Example
Document
└── html
    ├── head
    │   └── title → "My Page"
    └── body
        ├── h1 → "Hello"
        ├── p  → "Welcome"
        └── ul
            ├── li → "Item 1"
            └── li → "Item 2"

Selecting Elements

JavaScript
// Select by ID (returns one element)
const header = document.getElementById("header");

// Select by CSS selector (returns first match)
const btn = document.querySelector(".btn");
const h1  = document.querySelector("h1");
const nav = document.querySelector("nav a.active");

// Select all matching elements (returns NodeList)
const allBtns  = document.querySelectorAll(".btn");
const allItems = document.querySelectorAll("li");

// Iterate over NodeList
allBtns.forEach(btn => {
  console.log(btn.textContent);
});

Reading and Changing Content

JavaScript
const title = document.querySelector("h1");

// Read content
console.log(title.textContent);  // plain text
console.log(title.innerHTML);     // HTML including tags

// Change content
title.textContent = "New Title";
title.innerHTML = "<span style='color:red'>Red Title</span>";

Changing Styles

JavaScript
const box = document.querySelector(".box");

// Inline style (camelCase property names)
box.style.backgroundColor = "#6c63ff";
box.style.fontSize = "1.5rem";
box.style.display = "none";  // hide element

// Better: toggle classes
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("open");       // add if missing, remove if present
box.classList.contains("active");  // returns true/false

Changing Attributes

JavaScript
const link = document.querySelector("a");
const img  = document.querySelector("img");

// Get attribute
link.getAttribute("href");

// Set attribute
link.setAttribute("href", "https://annauniversityplus.com");
img.setAttribute("alt", "New description");

// Direct property access (for common attributes)
link.href = "https://example.com";
img.src   = "new-photo.jpg";

Creating and Inserting Elements

JavaScript
// Create a new element
const newItem = document.createElement("li");
newItem.textContent = "New Course";
newItem.classList.add("course-item");

// Append to existing element
const list = document.querySelector("ul");
list.appendChild(newItem);      // add at end
list.prepend(newItem);          // add at start

// Insert adjacent HTML (fastest)
list.insertAdjacentHTML("beforeend", "<li>Another item</li>");

// Remove element
newItem.remove();