The Document Object Model
Site Admin
· 11 Sep 2026
· 8 views
The Document Object Model
The DOM (Document Object Model) is the browser's in-memory representation of your HTML page. JavaScript uses the DOM to read, modify, and create page content dynamically.
Selecting Elements
// By ID (single element)
const header = document.getElementById("main-title");
// By CSS selector (first match)
const firstCard = document.querySelector(".card");
// By CSS selector (all matches)
const allCards = document.querySelectorAll(".card");
// By class name (all matches)
const buttons = document.getElementsByClassName("btn");
Reading and Changing Content
const heading = document.querySelector("h1");
heading.textContent = "New Title"; // Plain text only
heading.innerHTML = "<em>Styled Title</em>"; // Parses HTML
const p = document.querySelector("p");
console.log(p.textContent); // Read text
Attributes and Styles
const link = document.querySelector("a");
link.href = "https://example.com";
link.setAttribute("target", "_blank");
console.log(link.getAttribute("href"));
// Inline styles
const box = document.querySelector(".box");
box.style.backgroundColor = "#2563eb";
box.style.padding = "1rem";
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("selected");
box.classList.contains("active"); // true
Creating and Removing Elements
// Create and add
const item = document.createElement("li");
item.textContent = "New item";
const list = document.querySelector("ul");
list.appendChild(item); // Add at end
list.prepend(item); // Add at start
list.insertBefore(item, list.firstChild);
// Remove
item.remove(); // Remove directly
list.removeChild(item);
A Practical Example
const button = document.createElement("button");
button.textContent = "Add Item";
button.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = `Item ${list.children.length + 1}`;
list.appendChild(li);
});
document.body.appendChild(button);
Key Points
- The DOM is the browser's live model of the page.
- Use
getElementByIdandquerySelectorto find elements. textContentsets plain text;innerHTMLparses HTML.classListmanages CSS classes cleanly.createElement,appendChild, andremovebuild and tear down content.