Lesson 7 of 8 · 15 min · 1 hands-on step

The DOM & Events

Make pages interactive by reading and changing the page with JavaScript.

The DOM

When the browser loads HTML, it builds the DOM: a tree of objects you can read and change with JavaScript.

const title = document.querySelector("h1");
title.textContent = "Changed by JavaScript!";
title.classList.add("highlight");
  • document.querySelector(selector) finds the first match
  • document.querySelectorAll(selector) finds all matches

Events

Events are things that happen: clicks, key presses, form submits.

const button = document.querySelector("#save");
button.addEventListener("click", () => {
  console.log("Saved!");
});

Forms use the submit event. Call event.preventDefault() to stop the page from reloading:

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const email = form.elements.email.value;
});

State → UI

The pattern behind React, Vue and every modern framework is simple: keep your data in variables (state), and update the page from that data. You'll do exactly that in the exercise. Understanding it with plain JavaScript first makes frameworks much easier to learn later.

🧪 Practice

Build a like button:

  • Clicking #like increases the number shown in #count by 1
  • After any click, the button text changes to Liked ❤️

The tests click the button for you.

<button id="like">Like</button>
<p>Likes: <span id="count">0</span></p>

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What is the DOM?

  2. Why prefer textContent over innerHTML for user-provided text?

Create a free account to track your progress.