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.
<h1>Todo list</h1>
<input id="task" type="text">
<button id="add">Add</button>
<ul id="list"></ul>const input = document.querySelector("#task"); // by id
const list = document.querySelector("#list");
const items = document.querySelectorAll("li"); // every matchquerySelector takes the same selectors as CSS: #id, .class, tag, and combinations such as ul li.
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 classPrefer 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:
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.
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
<!-- your page here -->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
function toggleDone(todos, id) {
}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
function remaining(todos) {
}How a click becomes a change on the page.
The user clicks the Add button
The browser fires a
clickevent on that element.Your listener runs
The function you passed to
addEventListeneris called.It reads the input
input.valueholds what the user typed.It updates your data
Add a todo object to your array, using your plain functions.
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.
querySelectorfinds elements with CSS selectors;textContent,createElementandappendchange 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.
DOM checks.
Which selector finds the element with id="add"?
- A`.add`
- B`#add`
- C`add`
- D`[add]`
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
What does addEventListener("click", fn) do?
- ARuns `fn` now
- BRuns `fn` each time the element is clicked
- CDeletes the element
- DLoads a script
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
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.