DOM Manipulation and Browser APIsLesson 5.1
Selecting and modifying DOM elements with JavaScript
querySelector, querySelectorAll, getElementById, innerHTML vs textContent, createElement, appendChild, insertAdjacentHTML, removeElement, classList, dataset attributes
The DOM Is a Tree of Objects
The Document Object Model represents your HTML as a tree of JavaScript objects. Every element, text node, and attribute is a node. JavaScript selects these nodes and manipulates their properties to update what the user sees in real time — no page reload required. Learning the DOM API is what turns JavaScript knowledge into actual interactive UIs.
Selecting Elements
// Single element — returns first match or null
const btn = document.querySelector(".submit-btn");
const title = document.getElementById("page-title");
// Multiple elements — returns a static NodeList
const items = document.querySelectorAll("li.active");
items.forEach(item => item.classList.add("highlighted"));
Creating and Inserting Elements
const card = document.createElement("div");
card.className = "card";
card.textContent = "New card"; // safe — escapes HTML
document.querySelector(".container").appendChild(card);
// insertAdjacentHTML for building HTML from template strings
btn.insertAdjacentHTML("afterend",
`${count}`
);
Modifying Attributes and Classes
card.classList.add("active");
card.classList.remove("inactive");
card.classList.toggle("selected");
card.classList.contains("active"); // true
// data attributes — stored as strings
card.dataset.userId = "42";
card.getAttribute("data-user-id"); // "42"
textContent vs innerHTML
Use textContent when setting plain text — it escapes HTML characters and prevents XSS. Only use innerHTML with content you fully control and trust. Never pass unsanitized user input to innerHTML under any circumstances.
