Step 4 / 944%

Step 4

Step 4 — DOM Elements and State

15 min

Select the HTML elements and define the tasks array.

Definition

In programming, state refers to all the data an application keeps in memory at a given moment, describing "where it currently stands". In a to-do list, the state is the list of existing tasks, which ones are checked, which ones are not, and the filter currently selected. If you know the state, you can fully rebuild what the user sees on screen.

Selecting DOM elements is the operation of asking the browser to hand us elements of the HTML page (a form, a button, a list...) as JavaScript objects. Once these elements are stored in variables, we can read their content, modify them, add classes to them or attach event listeners to them.

These two notions are the foundation of almost every interactive web application: on one side the data (the state), on the other the entry points to the page (the selected elements).

Goal of this step

The visual side is finished. Now it's time for JavaScript! Before writing a single function, we prepare two things: grabbing the HTML elements we will need, and defining the application's state, meaning the data it works with.

This step may seem short, since nothing new appears on screen yet. Still, it is one of the most important in the project: all the code we write next (adding a task, checking it, deleting it, filtering the list) will build on the variables defined here. A good start avoids a lot of confusion later.

By the end of this step, you will have:

  • a todo.js file linked to your HTML page;
  • seven variables pointing to the elements of your page;
  • two variables representing your application's state;
  • the certainty that everything is properly connected, thanks to a few checks in the console.

Why separate state from the DOM?

When you're starting out, the natural reflex is to do everything directly in the HTML: to know whether a task is completed, you check whether it is struck through on screen. This works for a small example, but the application quickly becomes impossible to maintain: how do you count the remaining tasks, filter the list or save the data if the information only exists in the display?

The right approach is to separate two worlds:

  • the data world: a JavaScript array containing all the tasks, easy to modify, count, filter and save;
  • the display world: the HTML, which is only a "snapshot" of that data at a given moment.

Every time the data changes, we redraw the display from it. This principle will serve you in all your future projects, whatever framework you end up using.

Creating the todo.js file

Create the todo.js file next to the other two (it is already linked to your HTML through the <script defer> tag) and write this code:

todo.js
// ── 1. DOM elements ────────────────────────
const form = document.querySelector("#form");
const field = document.querySelector("#new-task");
const list = document.querySelector("#list");
const counter = document.querySelector("#counter");
const emptyMessage = document.querySelector("#empty-message");
const filterButtons = document.querySelectorAll(".filter");
const clearButton = document.querySelector("#clear-completed");

// ── 2. Application state ───────────────────
let tasks = [];
let activeFilter = "all";

Selecting DOM elements

We use querySelector only once per element, at the top of the file, then reuse the variables everywhere. It is more readable and more efficient than selecting the element again each time.

  • querySelector returns one element: the form, the field, the list, the counter, the empty message and the clear button.
  • querySelectorAll returns all matching elements: here, the three filter buttons.
  • These variables are declared with const: we will never reassign them.

Understanding selectors

The text passed to querySelector is a CSS selector, exactly the same as the ones you write in your stylesheet:

  • a selector starting with # targets an id, for example #list for the element with id="list";
  • a selector starting with . targets a class, for example .filter for all elements with class="filter".

Defining the application state

The whole application relies on a single source of truth: the tasks array. Each task is an object with three properties:

example of a task
{
  id: 1727700000000,
  text: "Learn the DOM",
  done: false
}
  • id: a unique identifier, which will let us find the task to check or delete.
  • text: what the user typed.
  • done: a boolean, true or false.
  • let activeFilter remembers the selected filter: "all", "active" or "completed". We use let because both tasks and activeFilter will change over time.

The golden rule: we modify the data first (the array), then we redraw the page from that data. We never store the information "this task is completed" only in the HTML.

Why a unique identifier?

Imagine two tasks with exactly the same text: "Do the shopping". If the user deletes the second one, how do we know which one to remove from the array? The text isn't enough, and the position in the list changes as soon as items are deleted or filtered. The id solves the problem: each task gets a number that belongs only to it.

In the example, the value 1727700000000 looks like a timestamp. This is intentional: later, we will use Date.now(), which returns the number of milliseconds elapsed since January 1, 1970. A human will never create two tasks in the same millisecond, so the identifier will indeed be unique.

const or let: which one to choose?

The choice depends on what you plan to do with the variable:

  • We use const when the variable will always point to the same thing. This is the case for our DOM elements: the form on the page will never be replaced by another one.
  • We use let when we plan to reassign the variable. This is the case for tasks, which we will replace with a new list after a deletion, and for activeFilter, which will go from "all" to "active" depending on the user's click.

When in doubt, start with const: if you need to reassign the variable, JavaScript will report the error and you can switch to let.

Screenshot of the todo.html page in the browser

Check your work

Reload the page and open the console (F12). No errors should appear. Then type these commands one by one:

browser console
console.log(form); // displays the <form>
console.log(filterButtons.length); // 3
console.log(tasks); // []

If one of these variables is null, the id or class used in querySelector doesn't match your HTML: check the spelling.

Your turn

In the console, try the following:

  1. Type field.value = "Test" and watch the input field fill in.
  2. Type list.classList.add("active") then inspect the element in the Elements tab: the class has indeed been added. Remove it with classList.remove.
  3. Type filterButtons.forEach(b => console.log(b.textContent)) and look at the labels of the three filter buttons.
  4. Type activeFilter = "active" then console.log(activeFilter) to see that the state variable has indeed changed (the page itself doesn't move yet: we'll deal with that later).