The DOM is the browser's live object model of your HTML. JavaScript reads and rewrites it, which is how pages respond to clicks, input and data without reloading. This is JavaScript's original superpower.
Both editors below are fully live — the HTML tab holds real markup and the JavaScript tab manipulates it.
Selecting elements
document.querySelector("#id"); // first match (or null)
document.querySelector(".card"); // any CSS selector works
document.querySelectorAll(".card"); // ALL matches, as a NodeList
// Older but perfectly fine for ids:
document.getElementById("main");Events — responding to the user
addEventListener(event, handler) is the standard way to react:
Change the handler: try doubling the count, or changing colors with
btn.style.background = "...".
Creating elements
Build nodes, then attach them:
Why textContent instead of innerHTML? If a user types
<img src=x onerror=alert(1)>, innerHTML would execute it — that's an
XSS attack. textContent treats everything as plain text. Only use
innerHTML for markup you wrote yourself.
Changing content, classes, styles
heading.textContent = "Plain text"; // safe
heading.classList.add("active"); // preferred over inline styles
heading.classList.toggle("open");
card.style.backgroundColor = "#eee"; // camelCase CSS property
link.setAttribute("href", "https://example.com");
link.dataset.userId = "42"; // becomes data-user-id="42"Event delegation
One listener on a parent handles events for all current AND future children — events "bubble up":
list.addEventListener("click", (e) => {
if (e.target.matches(".delete")) {
e.target.closest("li").remove();
}
});Forms without page reloads
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop the page reload
const data = Object.fromEntries(new FormData(form));
fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
});Knowledge Check
4 questions — test your understanding
textContent vs innerHTML?
document.querySelector(".card") returns...
Event delegation means...
Why call e.preventDefault() in a form submit handler?
Next: Async Programming