<htmlstart/>

JS DOM

The DOM API lets JavaScript read and change HTML elements on the page.

What is the DOM?

The Document Object Model is a tree of JavaScript objects representing every element on the page. JavaScript can read and modify this tree to change what the user sees.

Selecting Elements

// By ID (returns one element or null)
const title = document.getElementById("page-title");

// CSS selector — first match
const btn = document.querySelector(".btn");
const input = document.querySelector("input[type=email]");

// CSS selector — all matches (NodeList)
const cards = document.querySelectorAll(".card");

// Iterate NodeList
cards.forEach(card => card.classList.add("visible"));

Changing Content and Attributes

const el = document.getElementById("greeting");

// Text content (safe — escapes HTML)
el.textContent = "Hello!";

// HTML content (careful with user input — XSS risk)
el.innerHTML = "<strong>Hello!</strong>";

// Attributes
el.setAttribute("href", "/about");
el.getAttribute("class");
el.removeAttribute("hidden");

// Data attributes
el.dataset.userId = "42";  // sets data-user-id="42"
el.dataset.userId;         // "42"

Changing Styles and Classes

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

// Inline styles
box.style.color       = "red";
box.style.fontSize    = "18px";
box.style.display     = "none";  // hide
box.style.display     = "";      // show (remove inline style)

// Class manipulation (preferred)
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("open");        // add if missing, remove if present
box.classList.contains("active");    // true/false

Creating and Inserting Elements

// Create
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("list-item");

// Insert
document.querySelector("ul").appendChild(li);         // add at end
document.querySelector("ul").prepend(li);              // add at start
existingEl.insertAdjacentHTML("afterend", "<p>Hi</p>"); // insert HTML

// Remove
li.remove();
Use textContent when setting plain text — never use innerHTML with untrusted user input, as it executes any script tags and is a security risk (XSS).
🧩

Test Yourself

4 questions
Q1.Which method selects ALL elements matching a CSS selector?
Q2.Why should you use textContent instead of innerHTML for user input?
Q3.Which method adds a CSS class to an element?
Q4.What does element.remove() do?