JavaScript DOM Manipulation

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

JavaScript
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

JavaScript
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":

JavaScript
list.addEventListener("click", (e) => {
  if (e.target.matches(".delete")) {
    e.target.closest("li").remove();
  }
});

Forms without page reloads

JavaScript
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

1

textContent vs innerHTML?

2

document.querySelector(".card") returns...

3

Event delegation means...

4

Why call e.preventDefault() in a form submit handler?