From Zero to Senior · The LabالعربيةGitHub

Chapter 12

The DOM and Events

8 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • connect JavaScript to a web page with a <script> element
  • find elements on a page and change their text, classes and styles
  • create new elements and add them to the page
  • react to clicks, typing and form submissions with events
  • build a real, interactive shop page

Examples

12.2 Finding and changing elements

document.querySelector finds the first element that matches a CSS selector, the same selectors you learned in Chapter 6. Once you have an element, you can change it:

change.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Changing a page</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>Old title</h1>
    <p class="note">This paragraph will be highlighted.</p>
    <ul id="skills">
      <li>HTML</li>
      <li>CSS</li>
    </ul>
    <script src="change.js"></script>
  </body>
</html>
change.html560px
Figure 12.2: The page after the script has run. The HTML still says “Old title”; JavaScript changed it.

document.querySelector finds the first element that matches a CSS selector, the same selectors you learned in Chapter 6. Once you have an element, you can change it:

change.js⤓ File
// 1. Change text
const title = document.querySelector("h1");
title.textContent = "New title, set by JavaScript!";

// 2. Add a class (the CSS does the styling)
document.querySelector(".note").classList.add("highlight");

// 3. Create a new element and add it to the page
const item = document.createElement("li");
item.textContent = "JavaScript";
document.querySelector("#skills").append(item);

12.3 Events: reacting to people

An event is something that happens on the page: a click, a key press, a form being sent, the mouse moving. You tell an element what to do when an event happens with addEventListener:

counter.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Counter</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>Bit’s clicker</h1>
    <p id="output">You clicked 0 times</p>
    <button id="add">Click me</button>
    <button id="reset" class="secondary">Reset</button>
    <script src="counter.js"></script>
  </body>
</html>
counter.html560px
Figure 12.3: The counter after three clicks.

An event is something that happens on the page: a click, a key press, a form being sent, the mouse moving. You tell an element what to do when an event happens with addEventListener:

counter.js⤓ File
const output = document.querySelector("#output");
const addButton = document.querySelector("#add");
const resetButton = document.querySelector("#reset");

let count = 0;

function show() {
  output.textContent = `You clicked ${count} times`;
}

addButton.addEventListener("click", () => {
  count++;
  show();
});

resetButton.addEventListener("click", () => {
  count = 0;
  show();
});

12.4 Forms

Forms need one extra step. By default, sending a form reloads the page, which would wipe out everything your JavaScript did. event.preventDefault() stops that, so your code can handle the form itself:

greet.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Greeting</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <form id="greet">
      <label for="name">Your name</label>
      <input id="name" type="text">
      <button type="submit">Say hello</button>
    </form>
    <p id="output"></p>
    <script src="greet.js"></script>
  </body>
</html>
greet.html560px
Figure 12.4: After typing a name and pressing the button.

Forms need one extra step. By default, sending a form reloads the page, which would wipe out everything your JavaScript did. event.preventDefault() stops that, so your code can handle the form itself:

greet.js⤓ File
const form = document.querySelector("#greet");
const input = document.querySelector("#name");
const output = document.querySelector("#output");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const name = input.value.trim();
  if (name === "") {
    output.textContent = "Please type your name.";
    return;
  }
  output.textContent = `Hello, ${name}! Welcome to the web.`;
  input.value = "";
});

12.5 Project: Bit’s shop

Now let us put the shopping cart from Chapter 11 on a real page. The HTML is almost empty: a place for products and a place for the cart. JavaScript draws everything from the data:

shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="shop.css">
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section id="products"></section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
Figure 12.5: The shop after adding the book once and the sticker twice. The stylesheet, shop.css, is in the book’s code repository.

Now let us put the shopping cart from Chapter 11 on a real page. The HTML is almost empty: a place for products and a place for the cart. JavaScript draws everything from the data:

shop.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
  { id: 4, name: "Bit T-shirt", price: 15 },
];

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

renderProducts();
renderCart();
+ 1 files
shop.css⤓ File
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #f5f5fb; color: #1e1b2e; }
header { padding: 16px 24px; color: white; background: #4338ca; }
header h1 { margin: 0; }
main { display: grid; grid-template-columns: 1fr 240px; gap: 16px; padding: 16px 24px; }
#products { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; align-content: start; }
.card { background: white; border-radius: 14px; padding: 14px; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card p { margin: 0 0 10px; color: #db2777; font-weight: 700; }
.card button { width: 100%; padding: 8px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
#cart { background: white; border-radius: 14px; padding: 4px 16px 12px; align-self: start; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
#cart-lines { padding: 0; list-style: none; }
#cart-lines li { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid #eef2ff; }
#cart-total { font-weight: 700; font-size: 1.2rem; color: #4338ca; }
@media (max-width: 560px) { main { grid-template-columns: 1fr; } }

Practice projects

Project 12.1 · Easy

A night mode switch

One button switches the whole page between a day theme and a night theme, and its label always says what it will do next.

You will practise: querySelector, addEventListener, classList.toggle and classList.contains.

Steps
  1. Create theme.html with a heading, a paragraph and a button with id="theme".
  2. In the CSS, write the night colours under body.dark, for example body.dark { background: #1e1b4b; color: #e0e7ff; }.
  3. In theme.js, find the button and listen for "click".
  4. On each click, call document.body.classList.toggle("dark"): it adds the class if it is missing and removes it if it is there.
  5. Update the button’s textContent using classList.contains("dark") and the ternary operator.

Hint: JavaScript only switches a class; CSS decides how it looks. Keeping colours in CSS means a designer can change them without touching your script.

Solution
theme.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Night mode</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      body.dark { background: #1e1b4b; color: #e0e7ff; }
      body.dark h1 { color: #fbbf24; }
      body.dark button { background: #fbbf24; color: #1e1b4b; }
      p { max-width: 36em; line-height: 1.6; }
    </style>
  </head>
  <body>
    <h1>Bit’s reading room</h1>
    <p>Some people like bright pages; others read late at night. One button lets each reader choose.</p>
    <button id="theme">Switch to night</button>
    <script src="theme.js"></script>
  </body>
</html>
theme.html560px
Project 12.1: the reading room after one click.
theme.js⤓ File
const button = document.querySelector("#theme");

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");

  const isDark = document.body.classList.contains("dark");
  button.textContent = isDark ? "Switch to day" : "Switch to night";
});

Project 12.2 · Medium

A live character counter

As the reader types a message, show how many characters are left out of 120, and turn the number red when fewer than 20 remain.

You will practise: the input event, reading value, labels for form fields, and classList.toggle with a condition.

Steps
  1. Add a <label for="message">, a <textarea id="message" maxlength="120"> and a paragraph with <span id="left">120</span>.
  2. Listen for "input" on the text area. Unlike "change", it fires on every key press.
  3. Work out limit - message.value.length and show it in the span.
  4. Call left.classList.toggle("low", remaining < 20). With a second argument, toggle adds the class when the condition is true and removes it when it is false.
  5. Type, then delete some text, and watch the colour come back.

Hint: maxlength already stops the reader at 120. Your script does not enforce the limit; it only tells the reader where they stand. Good pages do both.

Solution
counter.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Message box</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      label { display: block; font-weight: 700; margin-bottom: 6px; }
      textarea { width: 100%; max-width: 30em; height: 6em; font: inherit; padding: 10px; border: 2px solid #c7d2fe; border-radius: 10px; }
      #left { font-weight: 700; color: #059669; }
      #left.low { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>Write a short message</h1>
    <label for="message">Your message</label>
    <textarea id="message" maxlength="120"></textarea>
    <p><span id="left">120</span> characters left</p>
    <script src="counter.js"></script>
  </body>
</html>
counter.html560px
Project 12.2: fewer than 20 characters left, so the number turns red.
counter.js⤓ File
const message = document.querySelector("#message");
const left = document.querySelector("#left");
const limit = 120;

message.addEventListener("input", () => {
  const remaining = limit - message.value.length;
  left.textContent = remaining;
  left.classList.toggle("low", remaining < 20);
});

Project 12.3 · Challenge

A quiz that builds itself

Write the questions as data, and let JavaScript build the buttons for each one, check the answer, move on, and show the score at the end.

You will practise: arrays of objects, createElement and append, replaceChildren, template literals, and splitting the work into functions.

Steps
  1. Create an array questions: each item has text, an options array, and answer, the index of the right option.
  2. Write show(): write the question number and text, clear the old buttons with options.replaceChildren(), then create one button per option with forEach.
  3. Each button calls choose(index). Compare it with answer, add a point if it is right, and show the feedback in green or red.
  4. Move to the next question. When there are none left, call finish() to show Your score: 2 / 3.
  5. In finish(), add a “Play again” button that resets current and points and calls show().
  6. Add two questions of your own to the array. The page grows without a single new line of HTML.

Hint: the data (questions, current, points) is the truth, and show() draws it on the page. This idea, “draw the page from the data”, is exactly how React and Vue work.

Solution
quiz.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Quiz</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      .card { max-width: 30em; background: white; border-radius: 16px; padding: 20px; box-shadow: 0 4px 14px rgb(67 56 202 / 0.12); }
      #options { display: flex; flex-direction: column; gap: 8px; margin: 14px 0; }
      #options button { background: #e0e7ff; color: #312e81; text-align: start; border-radius: 10px; }
      #feedback { min-height: 1.5em; font-weight: 700; }
      #feedback.right { color: #059669; }
      #feedback.wrong { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>Bit’s web quiz</h1>
    <div class="card">
      <p id="number"></p>
      <h2 id="question"></h2>
      <div id="options"></div>
      <p id="feedback"></p>
    </div>
    <script src="quiz.js"></script>
  </body>
</html>
quiz.html560px
…and shows the score at the end.
quiz.js⤓ File
const questions = [
  { text: "Which language gives a page its structure?", options: ["CSS", "HTML", "JSON"], answer: 1 },
  { text: "Which method finds one element on the page?", options: ["querySelector", "console.log", "JSON.parse"], answer: 0 },
  { text: "Which event fires when a button is pressed?", options: ["input", "submit", "click"], answer: 2 },
];

const number = document.querySelector("#number");
const question = document.querySelector("#question");
const options = document.querySelector("#options");
const feedback = document.querySelector("#feedback");

let current = 0;
let points = 0;

function show() {
  const q = questions[current];
  number.textContent = `Question ${current + 1} / ${questions.length}`;
  question.textContent = q.text;
  options.replaceChildren();

  q.options.forEach((option, index) => {
    const button = document.createElement("button");
    button.textContent = option;
    button.addEventListener("click", () => choose(index));
    options.append(button);
  });
}

function choose(index) {
  const q = questions[current];
  if (index === q.answer) {
    points++;
    feedback.textContent = "Correct!";
    feedback.className = "right";
  } else {
    feedback.textContent = `Not quite. The answer is ${q.options[q.answer]}.`;
    feedback.className = "wrong";
  }

  current++;
  if (current < questions.length) {
    show();
  } else {
    finish();
  }
}

function finish() {
  number.textContent = "";
  options.replaceChildren();
  question.textContent = `Your score: ${points} / ${questions.length}`;

  const again = document.createElement("button");
  again.textContent = "Play again";
  again.addEventListener("click", () => {
    current = 0;
    points = 0;
    feedback.textContent = "";
    again.remove();
    show();
  });
  options.append(again);
}

show();

Exercises

Exercise 12.1 · Easy

Add a “minus” button to the counter. Make sure the count never goes below zero.
The book's short answer
A third button whose handler does if (count > 0) count--; then show().
Show the solution
counter.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Counter</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>Bit’s clicker</h1>
    <p id="output">You clicked 0 times</p>
    <button id="add">Click me</button>
    <button id="minus">−</button>
    <button id="reset" class="secondary">Reset</button>
    <script src="counter.js"></script>
  </body>
</html>
counter.html640px
counter.js⤓ File
const output = document.querySelector("#output");
const addButton = document.querySelector("#add");
const minusButton = document.querySelector("#minus");
const resetButton = document.querySelector("#reset");

let count = 0;

function show() {
  output.textContent = `You clicked ${count} times`;
  // A button that cannot do anything should say so.
  minusButton.disabled = count === 0;
}

addButton.addEventListener("click", () => {
  count++;
  show();
});

// Never below zero: only subtract when there is something to subtract.
minusButton.addEventListener("click", () => {
  if (count > 0) {
    count--;
  }
  show();
});

resetButton.addEventListener("click", () => {
  count = 0;
  show();
});

show();

Exercise 12.2 · Easy

Add a button to your profile page from Chapter 7 that toggles a dark class on body, and write CSS for the dark theme.
The book's short answer
button.addEventListener("click", () => document.body.classList.toggle("dark")); and CSS for body.dark.
Show the solution
profile.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="dark.css">
    <title>About Sara</title>
  </head>
  <body>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="Sara’s avatar: a smiling purple robot" width="90" height="105">
      <h1>Sara Khan</h1>
      <p>Beginner web developer from Alexandria</p>
      <nav>
        <a href="#about">About</a> |
        <a href="#skills">Skills</a> |
        <a href="#contact">Contact</a>
      </nav>
      <button id="theme" type="button">Night mode</button>
    </header>

    <main>
      <section id="about">
        <h2>About me</h2>
        <p>I started learning to code this year with <em>Code from Zero</em>. I love building small tools that make life easier.</p>
      </section>

      <section id="skills">
        <h2>Skills I am learning</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>Contact</h2>
        <p>Write to me at <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>Built by Sara, with HTML and CSS.</p>
    </footer>
    <script src="theme.js"></script>
  </body>
</html>
profile.html640px
dark.css⤓ File
#theme {
  margin-top: 12px;
  padding: 6px 16px;
  border: 2px solid white;
  border-radius: 999px;
  color: white;
  background: transparent;
  font: inherit;
  cursor: pointer;
}

/* The night theme: everything that changes, under body.dark. */
body.dark {
  color: #e0e7ff;
  background-color: #0f0d1a;
}

body.dark header {
  background-color: #1e1b4b;
}

body.dark section {
  background-color: #1e1b2e;
  box-shadow: none;
}

body.dark h2 {
  color: #a5b4fc;
  border-color: #312e81;
}

body.dark a {
  color: #f9a8d4;
}

body.dark footer {
  color: #a5a3c0;
}
theme.js⤓ File
const button = document.querySelector("#theme");

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  // The label says what the button will do next.
  button.textContent = document.body.classList.contains("dark") ? "Day mode" : "Night mode";
});

Exercise 12.3 · Medium

Make a live character counter: below a <textarea>, show “42 / 280” and update it on every input event. Turn it red over 280.
The book's short answer
Listen to input, set the text to `${area.value.length} / 280`, and toggle a class when the length is over 280.
Show the solution
characters.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Character counter</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; max-width: 560px; }
      textarea { width: 100%; font: inherit; padding: 8px; box-sizing: border-box; }
      #count { font-weight: 700; color: #4338ca; }
      #count.over { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>Write a post</h1>
    <label for="post">Your post</label>
    <textarea id="post" rows="5"></textarea>
    <!-- aria-live: a screen reader announces the new count after each change. -->
    <p id="count" aria-live="polite">0 / 280</p>
    <script>
      const area = document.querySelector("#post");
      const count = document.querySelector("#count");
      const limit = 280;

      // "input" fires on every key press, paste and delete.
      area.addEventListener("input", () => {
        const length = area.value.length;
        count.textContent = `${length} / ${limit}`;
        count.classList.toggle("over", length > limit);
      });
    </script>
  </body>
</html>
characters.html640px

Exercise 12.4 · Medium

Add a “remove” button to each line of the shop’s cart.
The book's short answer
In renderCart, add a button to each line whose click handler removes the item from cart and calls renderCart().
Show the solution
shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="../../examples/shop.css">
    <style>
      #cart-lines li { align-items: center; gap: 8px; }
      #cart-lines span { margin-inline-start: auto; }
      .remove { border: 0; border-radius: 999px; padding: 2px 10px; color: #b91c1c; background: #fee2e2; font: inherit; cursor: pointer; }
    </style>
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section id="products"></section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
  { id: 4, name: "Bit T-shirt", price: 15 },
];

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

function removeFromCart(productId) {
  const i = cart.findIndex((item) => item.productId === productId);
  if (i !== -1) {
    cart.splice(i, 1);
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    // A remove button on every line. It changes the data, then redraws.
    const remove = document.createElement("button");
    remove.className = "remove";
    remove.textContent = "Remove";
    remove.setAttribute("aria-label", `Remove ${product.name}`);
    remove.addEventListener("click", () => removeFromCart(product.id));
    li.append(amount, remove);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

renderProducts();
renderCart();

Exercise 12.5 · Challenge

Add a search box above the products that shows only the products whose names contain the typed text, updating as the user types.
The book's short answer
Keep the search text in a variable; in renderProducts, loop over catalog.filter((p) => p.name.toLowerCase().includes(text.toLowerCase())), and redraw on every input event.
Show the solution
shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="../../examples/shop.css">
    <style>
      #cart-lines li { align-items: center; gap: 8px; }
      #cart-lines span { margin-inline-start: auto; }
      .remove { border: 0; border-radius: 999px; padding: 2px 10px; color: #b91c1c; background: #fee2e2; font: inherit; cursor: pointer; }
    </style>
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <div style="grid-column: 1 / -1">
        <label for="search">Search</label>
        <input id="search" type="search" placeholder="mug, sticker…">
      </div>
      <section id="products"></section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
  { id: 4, name: "Bit T-shirt", price: 15 },
];

const cart = [];

// What the reader has typed so far.
let searchText = "";

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  container.replaceChildren();
  // Only the products whose names contain the text, ignoring capital letters.
  const visible = catalog.filter((p) => p.name.toLowerCase().includes(searchText.toLowerCase()));
  if (visible.length === 0) {
    container.textContent = "No products match.";
  }
  for (const product of visible) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

function removeFromCart(productId) {
  const i = cart.findIndex((item) => item.productId === productId);
  if (i !== -1) {
    cart.splice(i, 1);
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    // A remove button on every line. It changes the data, then redraws.
    const remove = document.createElement("button");
    remove.className = "remove";
    remove.textContent = "Remove";
    remove.setAttribute("aria-label", `Remove ${product.name}`);
    remove.addEventListener("click", () => removeFromCart(product.id));
    li.append(amount, remove);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

document.querySelector("#search").addEventListener("input", (event) => {
  searchText = event.target.value.trim();
  renderProducts();
});

renderProducts();
renderCart();