The DOM and events

Select elements, change content and respond to clicks, input and submits.

Beginner 15 min read Lesson 10 of 480 Challenge included
What you will be able to do
  • Select elements with querySelector
  • Update content safely
  • Attach event listeners

The browser turns your HTML into a tree of objects called the DOM. JavaScript can read and change that tree, which is what makes a page interactive.

todo.jsJavaScript
const form = document.querySelector("#todo-form");
const input = document.querySelector("#todo-input");
const list = document.querySelector("#todo-list");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const text = input.value.trim();
  if (!text) return;

  const item = document.createElement("li");
  item.textContent = text;
  list.append(item);
  input.value = "";
  input.focus();
});
Live exampleA working counter
Your turn

Toggle a class

Easy

On button click, toggle the class "active" on #panel.

JAVASCRIPT · starter
const button = document.querySelector("#toggle");
const panel = document.querySelector("#panel");
// add a click listener
Check your understanding before moving on.
Knowledge checkQuestion 1

What does event.preventDefault() do on a form submit?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Async and fetch
Lesson 10 of 480 · 0% of course