JavaScript DOM Manipulation Basics
What is the DOM?
The Document Object Model is the browser’s live, in-memory representation of your HTML page. JavaScript can read and change it, and the page updates instantly.
Selecting Elements
const title = document.querySelector("h1"); const allButtons = document.querySelectorAll("button"); const box = document.getElementById("box"); querySelector and querySelectorAll accept any CSS selector, which makes them the most flexible choice for modern code.
Changing Content and Styles
title.textContent = "Welcome back!"; box.style.backgroundColor = "#f59e0b"; box.classList.add("highlight"); Responding to Events
const btn = document.querySelector("#save-btn"); btn.addEventListener("click", () => { console.log("Saved!"); }); Creating and Inserting Elements
const li = document.createElement("li"); li.textContent = "New item"; document.querySelector("ul").appendChild(li); Event Delegation
Instead of adding a listener to every list item, attach one listener to the parent and check what was clicked. This works even for items added later.
document.querySelector("ul").addEventListener("click", (e) => { if (e.target.tagName === "LI") { e.target.classList.toggle("done"); } }); Practice Exercise
Build a simple to-do list: an input and “Add” button that appends a new <li> to a list, and clicking any item toggles a “done” class on it.

Leave a Reply