Lesson 6 / 11

The DOM: Selecting and Updating Elements

The DOM (Document Object Model) is how JavaScript sees and changes a web page — every HTML element becomes an object your code can read, modify, or remove entirely.

const heading = document.querySelector("h1");
heading.textContent = "Updated by JavaScript";
heading.style.color = "#00f0ff";

querySelector accepts any CSS selector — a tag name, a class with a dot, an ID with a hash — and returns the first matching element. Use querySelectorAll to get every match as a list you can loop over.

Handling events

const button = document.querySelector(".btn");
button.addEventListener("click", () => {
  alert("Button clicked!");
});

addEventListener is the standard way to react to user interaction — clicks, key presses, form submissions, and more — and you can attach as many listeners as you want to the same element without them interfering with each other.

Reading form input

const input = document.querySelector("#username");
button.addEventListener("click", () => {
  console.log(`You typed: ${input.value}`);
});

Creating and removing elements

const li = document.createElement("li");
li.textContent = "New lesson unlocked";
document.querySelector("ul").appendChild(li);

// later:
li.remove();

This exact pattern — read an element, listen for an event, update the DOM — is what drives the checkmarks and progress bar on this very lesson page. Every interactive feature on a modern website ultimately boils down to this same loop.

A common mistake

Running document.querySelector(...) before the page has finished loading returns null, and calling a method on null crashes your script. Place your <script> tag at the end of the <body>, or wrap your code in a DOMContentLoaded event listener, to guarantee the HTML exists before your JavaScript tries to touch it.