Lesson 6 · Web development foundations

The DOM and events

Make pages interactive by building a working to-do list.

About 30 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

HTML describes a page and CSS styles it, but nothing on the page responds until JavaScript gets involved. The bridge between your code and the page is the DOM, and the way the page tells your code that something happened is events. Every interactive feature you've used on the web, from a "like" button to a checkout form to a chat window, is built from these two ideas. In this lesson you'll learn them by building a working to-do list.

The DOM is a tree of objects

When the browser parses HTML, it builds the Document Object Model: a tree where every element, and every piece of text, is an object (a node) with properties and methods. This HTML:

<main>
  <h1>Go-bag checklist</h1>
  <ul id="todo-list">
    <li>Water</li>
  </ul>
</main>

becomes a main node with two children, an h1 and a ul, and the ul has an li child that holds a text node. JavaScript reaches the tree through the global document object. Change a node and the browser updates the screen; you never redraw pixels yourself.

It's worth being precise here: the DOM is not your HTML file. The browser fixes mistakes as it parses, and scripts change the tree afterwards. The Elements panel in the developer tools shows the live DOM, which is why it can look different from "View source".

Finding elements

document.querySelector takes any CSS selector and returns the first matching element, or null if there's none. querySelectorAll returns all of them.

const list = document.querySelector('#todo-list')
const items = document.querySelectorAll('#todo-list li')

Because they use the CSS selectors you already know, these two methods are all most code needs. Store the result in a const near the top of your script and reuse it.

There's one timing rule: an element has to exist before you can find it. A script in the <head> runs before the browser has parsed the body, so querySelector returns null and the next line throws. Either put your <script> at the end of the <body> (as these playgrounds do), or add the defer attribute, <script src="app.js" defer>, which downloads the file in parallel and runs it once the HTML is parsed. Scripts loaded with type="module" are deferred automatically.

Changing elements

Once you have an element you can read and change it:

  • element.textContent = 'Packed' replaces its text.
  • element.classList.add('done'), .remove() and .toggle() change classes, which is the cleanest way to change appearance: let CSS define what .done looks like.
  • element.hidden = true hides it.
  • input.value reads or sets what's typed in a form field.

To add new content, create an element, fill it in and attach it:

const item = document.createElement('li')
item.textContent = 'Batteries'
list.append(item)

element.remove() takes an element out of the page.

Events

An event is the browser telling you something happened: a click, a key press, a form submission, the page finishing loading. You subscribe with addEventListener, giving it the event's name and a function to call:

const button = document.querySelector('#save')

button.addEventListener('click', (event) => {
  console.log('Saved!', event.target)
})

The function receives an event object with details. event.target is the element the event happened on; keyboard events carry event.key. Your function is called a listener or handler, and it runs every time the event fires, not just once.

Events you'll use constantly:

EventFires when
clickan element is clicked, tapped, or activated with Enter or Space if it's a button
inputthe value of a field changes, on every keystroke
changea field's value is committed, such as choosing from a <select>
submita form is submitted, by a submit button or by pressing Enter in a field
keydowna key is pressed
Question

Quick check

What does button.addEventListener('click', save()) do?
Pick an answer.

Forms and the submit event

For anything a user types and then confirms, use a real <form> and listen for submit on the form, rather than click on its button. You get Enter-to-submit for free, it works with assistive technology, and there's one place to handle it.

By default, submitting a form sends it to a server and loads a new page. In an app that handles the data in JavaScript, you stop that with event.preventDefault():

form.addEventListener('submit', (event) => {
  event.preventDefault()
  // read the fields and update the page
})

Event delegation

Events bubble: after firing on the element that was clicked, they fire on its parent, then its parent's parent, all the way up to document. That lets you put one listener on a container and handle clicks on any of its children, including ones you add later:

list.addEventListener('click', (event) => {
  const button = event.target.closest('button')
  if (button) button.closest('li').remove()
})

closest walks up from the clicked element to the nearest ancestor (or itself) that matches a selector. This pattern is called event delegation, and it's how lists of hundreds of items stay fast and simple: one listener instead of one per item.

Question

Quick check

You attach a click listener to every "Remove" button when the page loads. Items added later can't be removed. Why?
Pick an answer.

Build the to-do list

Challenge

A working to-do list

Make the checklist work:

  1. Listen for the form's submit event and call event.preventDefault().
  2. Trim the input's value. If it's empty, do nothing.
  3. Otherwise create an <li> holding the text (use textContent) and a Remove <button type="button">, add it to the list, and clear the input.
  4. Make the Remove buttons work, using one listener on the list.

Type something and press Add or Enter to test it after you press Run.

Console
  1. Nothing logged yet.
  • Adding an item puts it in the list
  • The input is cleared after adding
  • Empty or blank input doesn't add an item
  • What people type is shown as text, not run as HTML
  • Each item's Remove button removes it

From here to frameworks

At work you'll often use a framework such as React, Vue, Svelte or Angular. They exist because keeping the DOM in sync with your data by hand gets hard as apps grow: you describe what the page should look like for a given state, and the framework works out which DOM changes to make. Under the hood they still create elements, set text and attach event listeners exactly as you just did. Developers who understand the DOM debug framework problems much faster, and every framework's documentation assumes you know it.

Recap

  • The DOM is the browser's live tree of objects for the page; document.querySelector finds elements with CSS selectors.
  • Change pages with textContent, classList, createElement, append and remove; use textContent for user input to avoid XSS.
  • addEventListener runs your function every time an event fires; pass the function, don't call it.
  • Handle forms with the submit event and event.preventDefault().
  • Events bubble, so one listener on a container can handle all its children, including ones added later.

Finished this lesson?

Mark it complete to track your progress on this device.