Skip to content
Lesson 9 of 10 · JavaScript for Beginners

The DOM and events

See a web page as a tree you can read and change from JavaScript, and build the markup it works on.

20 min

A web page is written in HTML, the markup that says what is on the page. When the browser loads it, it builds a tree of objects called the DOM (Document Object Model). JavaScript reads and changes that tree, and the page updates.

html4 lines
<h1>Todo list</h1>
<input id="task" type="text">
<button id="add">Add</button>
<ul id="list"></ul>

javascript3 lines
const input = document.querySelector("#task");      // by id
const list  = document.querySelector("#list");
const items = document.querySelectorAll("li");      // every match

querySelector takes the same selectors as CSS: #id, .class, tag, and combinations such as ul li.

javascript5 lines
list.textContent = "";                    // set the text
const li = document.createElement("li");  // make a new element
li.textContent = input.value;             // read what the user typed
list.append(li);                          // add it to the page
li.classList.add("done");                 // add a CSS class

Prefer textContent to innerHTML when you insert user-typed text: innerHTML would run any HTML or script inside it.

An event is something that happens: a click, a key press. You attach a function that runs when it does:

javascript6 lines
document.querySelector("#add").addEventListener("click", () => {
  const li = document.createElement("li");
  li.textContent = input.value;
  list.append(li);
  input.value = "";
});

The DOM is awkward to test and slow to reason about. Put the real decisions in plain functions that take data and return data, then let a thin layer of DOM code call them. The next exercise does exactly that: first the page structure, then the logic.

The exercises in this course run JavaScript without a page, so you will build the HTML structure here and test the logic as functions. On your own computer, save the HTML in a file with a <script> at the end of the body, and open it in a browser to see the whole thing work.

The DOM is a tree. JavaScript finds a node and changes it.

Exercise4 checks
html

Write the HTML for the todo page.

Done when

  • An `h1` heading containing the word Todo
  • An `input` with `id="task"` and `type="text"`
  • A `button` with `id="add"` whose text is Add
  • A `ul` with `id="list"` containing at least two `li` items
starter code1 line
<!-- your page here -->
Exercise4 checks
javascript

Write toggleDone(todos, id). todos is an array of { id, text, done } objects. Return a new array in which the todo with that id has its done flipped (true to false, false to true). Other todos stay as they are, and the original array must not be changed.

Your code must satisfy

  • toggleDone([{id: 1, text: "a", done: false}, {id: 2, text: "b", done: false}], 2)→[{"id":1,"text":"a","done":false},{"id":2,"text":"b","done":true}]flips one
  • toggleDone([{id: 1, text: "a", done: true}], 1)→[{"id":1,"text":"a","done":false}]flips back
  • toggleDone([{id: 1, text: "a", done: false}], 9)→[{"id":1,"text":"a","done":false}]unknown id
  • (() => { const t = [{id: 1, text: "a", done: false}]; toggleDone(t, 1); return t[0].done; })()→falseoriginal untouched
starter code3 lines
function toggleDone(todos, id) {
  
}
Exercise3 checks
javascript

Write remaining(todos) that returns the text of every todo that is not done, as an array in the original order.

Your code must satisfy

  • remaining([{id: 1, text: "a", done: true}, {id: 2, text: "b", done: false}, {id: 3, text: "c", done: false}])→["b","c"]some done
  • remaining([{id: 1, text: "a", done: true}])→[]all done
  • remaining([])→[]empty
starter code3 lines
function remaining(todos) {
  
}
Steps
0/5

How a click becomes a change on the page.

  1. The user clicks the Add button

    The browser fires a click event on that element.

  2. Your listener runs

    The function you passed to addEventListener is called.

  3. It reads the input

    input.value holds what the user typed.

  4. It updates your data

    Add a todo object to your array, using your plain functions.

  5. It updates the page

    Create or change DOM elements so the page matches the data.

  • The DOM is the page as a tree of objects that JavaScript can read and change.
  • querySelector finds elements with CSS selectors; textContent, createElement and append change them.
  • addEventListener("click", fn) runs your function on an event.
  • Keep the logic in plain functions of data, so it is simple to test, and keep the DOM code thin.
Check yourself

DOM checks.

1Multiple choice

Which selector finds the element with id="add"?

  • A`.add`
  • B`#add`
  • C`add`
  • D`[add]`
2Multiple choice

Which is safer for putting user-typed text on a page?

  • A`el.innerHTML = text`
  • B`el.textContent = text`
  • CBoth are equally safe
  • DNeither works
3Multiple choice

What does addEventListener("click", fn) do?

  • ARuns `fn` now
  • BRuns `fn` each time the element is clicked
  • CDeletes the element
  • DLoads a script
4Put in order

Put these in the order they happen after a click on Add.

  • AIt reads the typed text
  • BIt adds a new li to the list
  • CThe click event fires
  • DYour listener function runs
5Fill the blanks

document.("#list") finds the first element matching a CSS selector.

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.