JavaScript: DOM, events and interactive pages

Lesson 10 of 17 · HTML, CSS and JavaScript

The browser turns HTML into a tree of objects – the DOM. Through the DOM, JavaScript finds elements, changes text, style and classes, creates new elements and reacts to clicks and input. At the end of the lesson we build a small "To-do list" app that remembers its data even after the browser is closed.

Before you start: required prior knowledge – JavaScript – first steps.
How to learn: do the tasks at the end on your own in your editor first; open the hint and the solution only after that. Every example has the code and a live result below it; type the code into your own file and change it.

DOM: the page as a tree

document
└── html
    ├── head
    │   └── title → "List"
    └── body
        ├── h1 → "My tasks"
        ├── input#newTask
        ├── button#add
        └── ul#list
            ├── li → "Learn the DOM"
            └── li → "Do homework"
Finding elementsReturns
document.getElementById("list")the element with id="list"
document.querySelector(".card")the first element that matches the CSS selector
document.querySelectorAll("li")all such elements (a list you can go through with for...of)

Changing content, style and classes

<style>
  .dark { background: #222; color: #eee; }
  .box { padding: 12px; border-radius: 8px; transition: background 0.3s; }
</style>
<div id="k" class="box">
  <h3 id="title">Title</h3>
  <p>Click the buttons:</p>
  <button id="b1">Change the text</button>
  <button id="b2">Dark theme</button>
  <button id="b3">Add an item</button>
  <ul id="list"></ul>
</div>
<script>
  const title = document.getElementById("title");
  const box   = document.getElementById("k");
  const list  = document.getElementById("list");
  let n = 0;

  document.getElementById("b1").addEventListener("click", () => {
    title.textContent = "Text changed at " + new Date().toLocaleTimeString("en");
  });
  document.getElementById("b2").addEventListener("click", () => {
    box.classList.toggle("dark");              // add the class if it is missing, remove it if it is there
  });
  document.getElementById("b3").addEventListener("click", () => {
    n++;
    const li = document.createElement("li");   // a new element
    li.textContent = "Item " + n;
    list.appendChild(li);                      // put it into the list
  });
</script>

Result:

StatementWhat it does
el.textContent = "..."changes the element's text
el.style.color = "red"changes one CSS property (names with a hyphen are written joined: backgroundColor)
el.classList.add / remove / toggle("name")adds, removes, toggles a class – better than changing styles one by one
document.createElement("li") + parent.appendChild(el)creates and inserts a new element
el.remove()deletes the element
input.valuethe text typed into the field
Security: insert text typed by the user with textContent, not with innerHTML. With innerHTML a typed <script> or <img onerror=...> would run – that is the XSS attack from the lesson Web application security.

Events

An event is something that happens on the page. A function that is called when the event happens is called an event listener:

element.addEventListener("click", function (e) {
  // e = data about the event (e.g. e.key for a key, e.target for the element)
});
EventWhen it happens
clicka mouse click or a tap
inputevery change of the text in a field
changea change of choice (select, checkbox)
submitsending a form
keydownpressing a key (e.key = "Enter", "ArrowUp"…)
mouseover / mouseoutthe mouse enters / leaves
DOMContentLoadedthe HTML has loaded (defer can be used instead)
<label>Type your name: <input id="name" type="text"></label>
<p id="greeting">Hello, ...!</p>
<label>Number: <input id="number" type="number" value="5"></label>
<p id="square"></p>
<script>
  const nameField = document.getElementById("name");
  nameField.addEventListener("input", () => {
    document.getElementById("greeting").textContent = "Hello, " + (nameField.value || "...") + "!";
  });

  const number = document.getElementById("number");
  function calculate() {
    const x = Number(number.value);        // text from the field -> number
    document.getElementById("square").textContent = `${x}² = ${x * x}`;
  }
  number.addEventListener("input", calculate);
  calculate();                             // calculate right away at the start
</script>

Result:

Handling a form in JavaScript

<form id="f">
  <label>Side a: <input name="a" type="number" required></label>
  <label>Side b: <input name="b" type="number" required></label>
  <button>Calculate</button>
</form>
<p id="res"></p>
<script>
  document.getElementById("f").addEventListener("submit", e => {
    e.preventDefault();                    // do NOT send the form to the server and do not reload the page
    const a = Number(e.target.a.value);
    const b = Number(e.target.b.value);
    if (a <= 0 || b <= 0) {
      document.getElementById("res").textContent = "The sides must be positive.";
      return;
    }
    document.getElementById("res").textContent = `Perimeter: ${2 * (a + b)}, area: ${a * b}`;
  });
</script>

Result:

e.preventDefault() stops the default behaviour (sending the form and reloading the page) – that way JavaScript handles the data itself.

Mini project: a to-do list that remembers

<style>
  body { font-family: system-ui, Arial, sans-serif; }
  .entry { display: flex; gap: 6px; }
  .entry input { flex: 1; padding: 6px; }
  ul { padding: 0; list-style: none; }
  li { display: flex; align-items: center; gap: 8px; padding: 6px; border-bottom: 1px solid #ddd; }
  li span { flex: 1; cursor: pointer; }
  li.done span { text-decoration: line-through; color: #999; }
  li button { border: 0; background: none; cursor: pointer; font-size: 1.1rem; }
</style>
<h3>My tasks</h3>
<form class="entry" id="form">
  <input id="newTask" placeholder="New task..." autocomplete="off">
  <button>Add</button>
</form>
<ul id="list"></ul>
<p id="counter"></p>
<script>
  // data: an array of objects { text, done }
  let tasks = [];
  try { tasks = JSON.parse(localStorage.getItem("tasks")) || []; } catch (e) {}

  function save() {
    try { localStorage.setItem("tasks", JSON.stringify(tasks)); } catch (e) {}
  }

  function render() {
    const list = document.getElementById("list");
    list.innerHTML = "";                         // clear the old list (no user text here)
    tasks.forEach((t, i) => {
      const li = document.createElement("li");
      if (t.done) li.classList.add("done");
      const text = document.createElement("span");
      text.textContent = t.text;                 // textContent – safe
      text.addEventListener("click", () => { t.done = !t.done; save(); render(); });
      const del = document.createElement("button");
      del.textContent = "✕";
      del.title = "Delete";
      del.addEventListener("click", () => { tasks.splice(i, 1); save(); render(); });
      li.append(text, del);
      list.appendChild(li);
    });
    const left = tasks.filter(t => !t.done).length;
    document.getElementById("counter").textContent = `Remaining: ${left} of ${tasks.length}`;
  }

  document.getElementById("form").addEventListener("submit", e => {
    e.preventDefault();
    const field = document.getElementById("newTask");
    const text = field.value.trim();
    if (text === "") return;
    tasks.push({ text: text, done: false });
    field.value = "";
    save();
    render();
  });

  render();
</script>

Result:

Key ideas:

  • data separated from the display – everything is in the array tasks; after every change the function render() draws the list again from the array;
  • localStorage – the browser keeps text under a key even after it is closed; the array is turned into text with JSON.stringify, and back with JSON.parse (the same JSON as in the lesson API and JSON);
  • localStorage belongs to one browser on one device – for data that other users see you need a backend with a database.

This app is the same idea as the To-do app in Flask (SR), except that there the server keeps the data.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked in the browser.

TASK 01Difficulty: easy

Switching the theme with a button

Make a "Dark theme" button that switches the page to a dark theme and back, while the button's text changes to "Light theme" and vice versa. The choice is remembered in localStorage.

TASK 02Difficulty: medium

The "Guess the number" game

The computer picks a number from 1 to 100. The user types a guess into a field and clicks "Check"; below it the page shows "Higher", "Lower" or "Correct in N tries!". A "New game" button picks a new number.

Common mistakes and tips
  • A script that looks for an element before it has loaded gets null – put the <script> at the end of body or use defer.
  • The value from a field is always text – convert it with Number().
  • In a form handled by JavaScript do not forget e.preventDefault(), otherwise the page reloads.
  • Insert user text with textContent, not with innerHTML.

Check your knowledge

Open the quiz

DOM and events

1. What does document.querySelector(".card") return?




2. How do you safely put text typed by the user into an element?



3. What is e.preventDefault() for in a submit event?




4. Where does localStorage keep data?