NelsonLabs
JavaScript Basics/The DOM — Talking to the Page

The DOM — Talking to the Page

The DOM (Document Object Model) is the browser's in-memory representation of your HTML page as a tree of objects. JavaScript can read and modify that tree — which is how it changes what users see without reloading the page.

ANALOGY

The DOM is a live map of your page. When the browser loads your HTML, it builds a tree structure — every element becomes a node, with parents, children, and siblings. JavaScript can walk this tree, find elements, read their content, change their styles, add new elements, and remove old ones. All in real-time, with no page reload.

Selecting elements
javascript
// querySelector — returns the first matching element (like CSS selectors)
const heading   = document.querySelector("h1");
const card      = document.querySelector(".card");
const submitBtn = document.querySelector("#submit-btn");
const firstLink = document.querySelector("nav a");

// querySelectorAll — returns ALL matching elements (as a NodeList)
const allCards   = document.querySelectorAll(".card");
const allButtons = document.querySelectorAll("button");

// Loop over NodeList
allCards.forEach(card => {
  card.style.border = "1px solid red";
});

// Older methods (still used, but querySelector is cleaner)
document.getElementById("main-title");      // single element
document.getElementsByClassName("card");    // HTMLCollection
document.getElementsByTagName("p");         // HTMLCollection
Reading and changing content
javascript
const heading = document.querySelector("h1");

// Reading
heading.textContent   // plain text — no HTML tags
heading.innerHTML     // HTML string including any child tags

// Writing
heading.textContent = "New Heading Text";  // safer — treats value as text
heading.innerHTML   = "Hello <strong>World</strong>";  // parses HTML

// Manipulating styles
const box = document.querySelector(".box");
box.style.color           = "#C96A30";
box.style.backgroundColor = "#201D15";
box.style.padding         = "1rem";
box.style.display         = "none";  // hide

// Better: toggle CSS classes instead
box.classList.add("visible");
box.classList.remove("hidden");
box.classList.toggle("active");
box.classList.contains("active");  // true/false
Creating and removing elements
javascript
// Create a new element
const newCard = document.createElement("div");
newCard.classList.add("card");
newCard.textContent = "I was created by JavaScript";

// Add it to the page
document.querySelector(".grid").appendChild(newCard);
document.querySelector(".grid").prepend(newCard);  // add at start

// More precise insertion
const reference = document.querySelector(".existing-card");
reference.before(newCard);  // insert before the reference
reference.after(newCard);   // insert after the reference

// Remove an element
const staleCard = document.querySelector(".old");
staleCard.remove();