⚡ Lesson 11 of 30
DOM Manipulation
Select, create, modify, and remove HTML elements using the Document Object Model API.
Selecting Elements
// By ID
const title = document.getElementById("title");
// CSS selector (first match)
const btn = document.querySelector(".btn-primary");
// All matches
const items = document.querySelectorAll("li");
items.forEach(item => console.log(item.textContent));
Reading & Writing Content
const el = document.querySelector("#message");
el.textContent = "Hello from JS!"; // safe — no HTML parsing
el.innerHTML = "Bold!"; // parses HTML
console.log(el.textContent); // plain text
Changing Styles & Classes
const box = document.querySelector(".box");
box.style.backgroundColor = "#f7c948";
box.style.padding = "1rem";
box.classList.add("visible");
box.classList.remove("hidden");
box.classList.toggle("active");
console.log(box.classList.contains("visible")); // true
Creating & Inserting Elements
const ul = document.querySelector("ul");
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("item");
ul.appendChild(li); // add at end
ul.prepend(li); // add at start
ul.insertBefore(li, ul.firstChild); // before specific node
Removing Elements & Attributes
const el = document.querySelector("#old");
el.remove(); // remove from DOM
const img = document.querySelector("img");
console.log(img.getAttribute("src")); // read attribute
img.setAttribute("alt", "A photo"); // set attribute
img.removeAttribute("title"); // remove attribute