HTMLstructure CSSstyle JSbehavior browser engine <header> My Site <nav> <main> click me
PLATE 0 — Bones, skin, and muscles: three languages, one page.
A picture book for grown-ups · with code

How the Web Works, and How to Build For It

Fifteen spreads in three parts: HTML for structure, CSS for style, JavaScript for behavior. Each has a picture, the idea, and code you can paste into a file and open in a browser.

Say it like a pro

"Semantic, accessible HTML first; a mobile-first CSS layout with grid, flexbox and custom properties; then progressive enhancement with vanilla JS: event delegation, async/await fetches, and state in localStorage."

Every phrase in that sentence gets its own page. Use the tabs or the ← → keys.

browser server DNS → 93.184.x.x GET /index.html HTTP/2 200 OK · text/html then the HTML asks for more GET /style.css GET /app.js GET /logo.png status codes 200 OK 301 moved 304 use your cache 400 bad req 401/403 not allowed 404 not found 500 server broke 503 server busy 2xx good · 3xx go elsewhere · 4xx your fault · 5xx theirs
PLATE 1 — Ask, receive, ask again. A page is a conversation of many requests.
Part 1 · HTML · Chapter 1 · The web & your setup

What happens when you hit Enter

The browser looks up the domain (DNS), sends an HTTP request, gets back HTML, then fetches every CSS, JS and image file the HTML mentions. The browser turns all of it into pixels.

Your setup

  1. Install VS Code and the Live Server extension (reloads on save).
  2. Make a folder with index.html, style.css, app.js.
  3. Right-click index.html → Open with Live Server.
  4. Press F12 for DevTools: Elements, Console, Network.
Terminal · or serve a folder without extensions
$ mkdir my-site && cd my-site
$ python -m http.server 8000       # → http://localhost:8000
$ npx serve .                       # if you have Node
URL
https://shop.com:443/cart?id=7#top → scheme · host · port · path · query · fragment
HTTPS
HTTP inside TLS encryption; required for most modern APIs
DevTools
Network tab shows every request; Console shows every error
anatomy of an element <a href="/about">About us</a> openattributecontentclose void elementshave no close:<img> <br> <input> the document is a tree (the DOM) html head body title meta h1 p ul li li head = info about the page · body = what you see
PLATE 2 — Tags nest like a family tree. CSS and JS both walk this tree.
Part 1 · HTML · Chapter 2 · Elements & the skeleton

Every page starts with the same bones

HTML is made of elements: an opening tag, optional attributes, content, and a closing tag. Elements nest inside each other, and the browser builds them into a tree called the DOM.

index.html · type ! + Tab in VS Code
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My First Site</title>
  <link rel="stylesheet" href="style.css">
  <script src="app.js" defer></script>
</head>
<body>
  <h1>Hello, web!</h1>
  <p>This is <strong>important</strong> and <em>stressed</em>.</p>
  <ul>
    <li>HTML</li>
    <li>CSS</li>
  </ul>
  <!-- comments look like this -->
</body>
</html>
viewport
without that meta tag, phones show a tiny zoomed-out desktop page
defer
download JS now, run it after the HTML is parsed
block / inline
<div> <p> <h1> start new lines · <span> <a> <strong> flow in text
<header> <nav> Home · Blog <main> <article> <h1> <section> <aside> <footer> vs. div soup <div class=…> <div class=…> <div class=…> same look, butscreen readers,search engines andteammates can'ttell what's what one <h1> per pagethen h2 → h3 inorder, no skipping
PLATE 3 — Name each region for what it is, not how it looks.
Part 1 · HTML · Chapter 3 · Semantic layout & text

Tags that say what things are

Semantic elements describe meaning. Screen readers use them to jump between regions, search engines use them to understand content, and you'll thank yourself when reading the code later.

layout.html · inside <body>
<header>
  <a href="/" class="logo">Ada's Blog</a>
  <nav aria-label="Main">
    <ul>
      <li><a href="/" aria-current="page">Home</a></li>
      <li><a href="/about">About</a></li>
    </ul>
  </nav>
</header>

<main>
  <article>
    <h1>Why Semantics Matter</h1>
    <p>Posted <time datetime="2026-10-29">Oct 29</time></p>
    <h2>The short version</h2>
    <blockquote>Use the right tag for the job.</blockquote>
  </article>
  <aside>Related posts…</aside>
</main>

<footer>© 2026 Ada</footer>
article
stands on its own (a post, a product card)
section
a themed chunk with its own heading
div / span
no meaning at all; use only for styling hooks
paths · how links find files site/ ├─ index.html ├─ about.html └─ img/ └─ cat.jpg from index.html: about.html relative img/cat.jpg relative /img/cat.jpg site root https://… absolute #contact same page alt text · the picture, in words 🔊 "Orange cat asleep on a laptop" <picture> · right size per screen 400w 1600w
PLATE 4 — Links follow paths; images need words for people who can't see them.
Part 1 · HTML · Chapter 4 · Links, images & media

Connect pages and show things

The <a> tag links anywhere with href. Images need alt text that describes them (or alt="" if they're decoration). Give images width and height so the page doesn't jump while they load.

media.html
<a href="about.html">About</a>
<a href="https://mdn.dev" target="_blank" rel="noopener">MDN</a>
<a href="#contact">Jump to contact</a>
<a href="mailto:hi@ada.dev">Email me</a>

<img src="img/cat.jpg" alt="Orange cat asleep on a laptop"
     width="800" height="600" loading="lazy">

<picture>
  <source srcset="hero.avif" type="image/avif">
  <img src="hero.jpg" alt="Mountain at sunrise"
       srcset="hero-400.jpg 400w, hero-1600.jpg 1600w"
       sizes="(max-width: 600px) 100vw, 50vw">
</picture>

<figure>
  <video src="demo.mp4" controls muted playsinline></video>
  <figcaption>A 10-second demo</figcaption>
</figure>
loading=lazy
don't download images until they're near the screen
formats
photos: AVIF / WebP / JPG · logos & icons: SVG · screenshots: PNG
Sign up Name Ada Email ada@ ⚠ Please enter a valid email Send me updates Create <label for="name">↔ <input id="name">click label = focus input type="email" + required= free validation POST name=Ada &email=… a11y: labels · keyboard (Tab/Enter) · contrast 4.5:1 · focus outline
PLATE 5 — Every input gets a label, and the browser checks the basics for you.
Part 1 · HTML · Chapter 5 · Forms & accessibility

Collect input that everyone can use

Forms gather data. Pick the right type and phones show the right keyboard, and the browser validates it for free. Tie every input to a <label>: it's the single biggest accessibility win.

signup.html
<form action="/signup" method="post">
  <label for="name">Name</label>
  <input id="name" name="name" required autocomplete="name">

  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>

  <label for="age">Age</label>
  <input id="age" name="age" type="number" min="13" max="120">

  <label for="plan">Plan</label>
  <select id="plan" name="plan">
    <option>Free</option><option>Pro</option>
  </select>

  <fieldset>
    <legend>Contact me by</legend>
    <label><input type="radio" name="via" value="email" checked> Email</label>
    <label><input type="radio" name="via" value="sms"> SMS</label>
  </fieldset>

  <button type="submit">Create account</button>
</form>
name
the key sent to the server; without it, the field isn't sent
button
use <button> for actions, <a> for navigation, never a clickable <div>
ARIA
only when no HTML element fits; "no ARIA beats bad ARIA"
Say it like a pro

"Unplug your mouse and Tab through the page. If you can't do everything with a keyboard, it's not done."

anatomy of a rule .card h2 { color: navy; } selectorpropertyvalue who wins? specificity scoreboard selectoridclasselem button001 .btn.primary020 #buy100← wins compare left to right: one id beats any number of classes tie? the rule written later wins inline style="" beats all · !important beats that (avoid it) inherited (color, font) comes from the parent if nothing sets it
PLATE 6 — When rules fight, the more specific one wins; ties go to the last one.
Part 2 · CSS · Chapter 6 · Selectors & the cascade

Pick elements, then decide who wins

A CSS rule is a selector plus declarations. When several rules hit the same element, the cascade picks one: importance, then specificity, then source order. Keep specificity low and flat (mostly single classes) and you'll rarely fight it.

style.css
/* element · class · id · attribute */
p            { line-height: 1.6; }
.card        { border: 1px solid #ccc; }
#hero        { min-height: 60vh; }
a[href^="http"] { text-decoration: underline dotted; }

/* combinators */
.card h2     { margin: 0; }          /* any h2 inside .card */
.nav > li    { display: inline; }    /* direct children only */
h2 + p       { font-size: 1.1rem; }  /* p right after h2 */

/* states and positions */
a:hover, a:focus-visible { color: crimson; }
li:nth-child(odd)        { background: #f6f6f6; }
input:invalid            { border-color: red; }
.card:has(img)           { padding: 0; }   /* parent selector! */
.btn::after              { content: " →"; }

/* group, then reset sanely */
*, *::before, *::after { box-sizing: border-box; }
img { max-width: 100%; display: block; }
:pseudo-class
a state: :hover :focus :checked :first-child
::pseudo-element
a part: ::before ::after ::placeholder ::first-line
BEM
naming like .card__title--big keeps classes flat and clear
marginoutside border paddinginside content200 × 70 width content-box (default) width 200 + padding 40+ border 4 = 244 wide 😬 border-box ✓ width 200 means 200,padding fits inside
PLATE 7 — Every element is a box inside a box inside a box.
Part 2 · CSS · Chapter 7 · The box model & units

Content, padding, border, margin

Every element is a rectangle. Padding is space inside the border, margin is space outside it. Set box-sizing: border-box everywhere so width means what you think it means.

box.css
*, *::before, *::after { box-sizing: border-box; }

.card {
  width: min(100%, 40rem);         /* fluid, but capped */
  padding: 1.5rem;                 /* all four sides */
  padding-inline: 2rem;            /* left + right */
  margin: 2rem auto;               /* auto = center it */
  border: 2px solid #152430;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgb(0 0 0 / .1);
}

.stack > * + * { margin-block-start: 1rem; }  /* space between kids */

.title {
  font-size: clamp(1.5rem, 4vw, 3rem);  /* min, ideal, max */
}
.hidden-but-readable {
  position: absolute; width: 1px; height: 1px;
  overflow: hidden; clip-path: inset(50%);
}
UnitRelative toUse for
pxnothing (fixed)borders, shadows
remroot font sizefont sizes, spacing
emthis element's fontpadding on buttons
%parent sizewidths
vw / vh / dvhthe viewportfull-screen sections
chwidth of "0"readable lines: max-width: 65ch
collapse
vertical margins between blocks merge: 20px + 30px = 30px, not 50px
display: flex · items line up on the main axis main axis → cross ↓ justify-content (along main) flex-start space-between center align-items (across)flex: 1 · take what's left flex-start flex: 1
PLATE 8 — Flexbox lines things up in one direction and shares out the spare room.
Part 2 · CSS · Chapter 8 · Flexbox

Line things up in one direction

Flexbox is for one-dimensional layouts: a row of buttons, a nav bar, a card's header. Put display: flex on the parent; the children become flex items.

flex.css
/* nav bar: logo left, links right, vertically centered */
.site-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

/* perfectly center anything */
.center {
  display: flex;
  place-content: center;    /* or justify + align: center */
  min-height: 100dvh;
}

/* input that grows, button that doesn't */
.search       { display: flex; gap: .5rem; }
.search input { flex: 1; }              /* grow into spare space */
.search button{ flex-shrink: 0; }

/* wrap onto new lines on small screens */
.tags         { display: flex; flex-wrap: wrap; gap: .5rem; }

/* a column, with the footer pushed to the bottom */
.card         { display: flex; flex-direction: column; }
.card .footer { margin-top: auto; }
gap
space between items; no more margin hacks
flex: 1
short for grow 1, shrink 1, basis 0: "share the space equally"
order
reorders visually only; screen readers still follow the HTML order
grid-template-areas · draw the layout in text header sidebar main footer 200px1fr auto-fit · as many columns as fit phone: 1 desktop: 4 · no media query needed
PLATE 9 — Grid handles rows and columns at once. Flexbox for a line, grid for a layout.
Part 2 · CSS · Chapter 9 · Grid

Lay out rows and columns together

CSS Grid is two-dimensional. Define columns and rows on the parent, then place children by line number or by named area. The fr unit means "a fraction of the leftover space".

grid.css
.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  gap: 1rem;
  min-height: 100dvh;
}
.page > header { grid-area: header; }
.page > aside  { grid-area: sidebar; }
.page > main   { grid-area: main; }
.page > footer { grid-area: footer; }

/* the famous responsive card grid, zero media queries */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 1.5rem;
}

/* make one card span two columns */
.cards .featured { grid-column: span 2; }

/* line numbers: from line 1 to the last line */
.banner { grid-column: 1 / -1; }
fr
1fr 2fr → the second column gets twice the spare space
minmax
"at least 220px, at most an equal share"
subgrid
children line up with the parent's tracks (cards with aligned buttons)
Say it like a pro

"Grid for the page, flex for the components inside it."

mobile first · add columns as the screen grows base ≥ 600px ≥ 1000px custom properties · change once, update everywhere :root light --bg --text --brand prefers dark same names, new values
PLATE 10 — Start small and add layout as space appears. Name your colors once.
Part 2 · CSS · Chapter 10 · Responsive design & custom properties

One stylesheet, every screen, light and dark

Write the phone layout first, then use media queries to add columns on wider screens. Store colors and spacing in custom properties (CSS variables) so a theme switch is just new values.

theme.css
:root {
  --bg: #ffffff;
  --text: #152430;
  --brand: #2F5BEA;
  --space: 1rem;
  --radius: 10px;
}
@media (prefers-color-scheme: dark) {
  :root { --bg: #0F161C; --text: #E6EDF1; --brand: #6E8FFF; }
}

body   { background: var(--bg); color: var(--text); }
.btn   { background: var(--brand); padding: var(--space);
         border-radius: var(--radius); }
.btn:hover { background: color-mix(in oklch, var(--brand), black 15%); }

/* mobile first: one column by default */
.products { display: grid; gap: var(--space); }

@media (min-width: 600px)  { .products { grid-template-columns: 1fr 1fr; } }
@media (min-width: 1000px) { .products { grid-template-columns: repeat(3, 1fr); } }

/* respond to the container, not the screen */
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) { .card { display: flex; } }

@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}
transition
transition: transform .2s ease; animates any change smoothly
test
DevTools → device toolbar (Ctrl+Shift+M) to try phone sizes
declare a variable constcan't reassign letcan reassign varold, leaky scope primitive types string"hi" number42, 3.14 booleantrue nullempty on purpose undefinednever set functions · two ways to write the same thing function add(a, b) { return a + b; } const add = (a, b) => a + b; arrow function
PLATE 11 — Default to const, use let when it must change, forget var.
Part 3 · JavaScript · Chapter 11 · The basics

Values, variables, and functions

JavaScript runs in every browser. Open DevTools → Console and type along. Use const by default, let if you'll reassign. Always use === (strict equality), which never converts types behind your back.

app.js · or paste into the Console
const name = "Ada";
let score = 0;
score += 10;

console.log(`Hi ${name}, score: ${score}`);   // template literal
Hi Ada, score: 10

console.log(typeof 42, typeof "42", typeof null);
number string object             // null is a famous bug

console.log(1 == "1", 1 === "1");
true false                       // == converts, === doesn't

function greet(who = "friend") {
  return `Hello, ${who}!`;
}
const shout = (text) => text.toUpperCase() + "!";
console.log(greet(), shout("hey"));
Hello, friend! HEY!

const age = 20;
const label = age >= 18 ? "adult" : "minor";   // ternary

for (let i = 0; i < 3; i++) console.log(i);

const user = null;
console.log(user?.name ?? "guest");    // optional chaining + nullish
guest
falsy
false 0 "" null undefined NaN; everything else is truthy
??
fallback only for null/undefined; || also replaces 0 and ""
"use strict"
automatic inside modules and classes; catches silent mistakes
the array pipeline $5out$3$2 products .filter(inStock) .map(p => p.price) [5, 3, 2] .reduce(sum) → 10 object · labeled drawers name: "Lamp" price: 5 tags: ["home"] product.name → "Lamp" product["price"] → 5 destructure · unpack by name const { name, price } = product spread · copy and extend { ...product, price: 4 } [...list, newItem]
PLATE 12 — Filter what you need, map it into shape, reduce it to an answer.
Part 3 · JavaScript · Chapter 12 · Arrays & objects

Collections, and the methods that tame them

An array is an ordered list, an object is a set of named properties. Modern JS chains array methods instead of writing loops, and uses spread to make copies instead of changing data in place.

data.js
const products = [
  { name: "Lamp",  price: 5, inStock: true },
  { name: "Chair", price: 9, inStock: false },
  { name: "Mug",   price: 3, inStock: true },
];

const total = products
  .filter(p => p.inStock)
  .map(p => p.price)
  .reduce((sum, n) => sum + n, 0);
console.log(total);
8

const mug = products.find(p => p.name === "Mug");
const anyCheap = products.some(p => p.price < 4);
const byPrice = products.toSorted((a, b) => a.price - b.price);

const { name, price = 0 } = mug;            // destructuring
const [first, ...rest] = products;

const discounted = { ...mug, price: 2 };    // copy + change
const more = [...products, { name: "Pen", price: 1 }];

for (const [key, value] of Object.entries(mug)) {
  console.log(key, value);
}

const json = JSON.stringify(mug);           // object → text
const back = JSON.parse(json);              // text → object
for…of
loops over values of arrays, strings, maps; for…in loops over keys (avoid on arrays)
references
const b = a shares one array; [...a] or structuredClone(a) copies
Map / Set
new Map() for any-key lookups, new Set(arr) to dedupe
app.jsquerySelector body ul#todos 1 listenerlives here li li li button ✕ click bubbles up ↑ the loop of every interactive page 1 select elements 2 listen for events 3 update your data 4 re-render the DOM textContent for text · never innerHTML with user input
PLATE 13 — Events bubble up the tree, so one listener on the parent can handle every child.
Part 3 · JavaScript · Chapter 13 · The DOM & events

Make the page react

The DOM is the live tree of your HTML that JS can read and change. Grab elements with querySelector, react to events with addEventListener, and change content, classes and attributes.

dom.js · loaded with <script defer>
const form  = document.querySelector("#add-form");
const input = document.querySelector("#new-todo");
const list  = document.querySelector("#todos");
const items = document.querySelectorAll(".todo");   // all matches

form.addEventListener("submit", (event) => {
  event.preventDefault();                 // stop the page reload
  const text = input.value.trim();
  if (!text) return;

  const li = document.createElement("li");
  li.className = "todo";
  li.textContent = text;                  // safe: no HTML parsed
  const del = document.createElement("button");
  del.textContent = "✕";
  del.setAttribute("aria-label", `Delete ${text}`);
  li.append(del);
  list.append(li);
  input.value = "";
  input.focus();
});

// event delegation: one listener for every current AND future button
list.addEventListener("click", (event) => {
  const btn = event.target.closest("button");
  if (btn) btn.parentElement.remove();
});

list.addEventListener("dblclick", (e) => {
  e.target.closest("li")?.classList.toggle("done");
});

document.body.dataset.theme = "dark";     // sets data-theme="dark"
events
click input change submit keydown scroll DOMContentLoaded
classList
.add .remove .toggle .contains; let CSS do the styling
XSS
innerHTML = userText lets attackers inject scripts; use textContent
your page api fetch("/api/users") … 300 ms later · JSON a Promise is a restaurant pager pendingwaiting…page still works fulfilled ✓ rejected ✕ → await gives data→ catch the error const res = await fetch(url); const data = await res.json(); await = "pause this function until the pager buzzes" the rest of the page keeps going meanwhile
PLATE 14 — Ask for data, keep working, and pick it up when it arrives.
Part 3 · JavaScript · Chapter 14 · Async, fetch & promises

Talk to servers without freezing the page

Network requests take time. JS doesn't stop and wait; fetch returns a Promise right away. Inside an async function, await pauses just that function until the result is ready. Wrap it in try/catch for failures.

api.js
async function loadUsers() {
  const status = document.querySelector("#status");
  status.textContent = "Loading…";
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);   // fetch won't throw on 404
    const users = await res.json();
    renderUsers(users);
    status.textContent = `${users.length} users`;
  } catch (err) {
    status.textContent = "Couldn't load users.";
    console.error(err);
  }
}

function renderUsers(users) {
  const ul = document.querySelector("#users");
  ul.replaceChildren(...users.map(u => {
    const li = document.createElement("li");
    li.textContent = `${u.name} · ${u.email}`;
    return li;
  }));
}

// send data
await fetch("/api/todos", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ text: "Learn fetch" }),
});

// run several at once, wait for all
const [posts, users] = await Promise.all([
  fetch("/api/posts").then(r => r.json()),
  fetch("/api/users").then(r => r.json()),
]);

setTimeout(() => console.log("1s later"), 1000);
loadUsers();
CORS
browsers block calls to other sites unless that server allows it; it's the server's setting
event loop
JS runs one thing at a time; async work queues callbacks for later
My Tasks What needs doing? Add ☐ Learn grid✕ ☑ Write HTML✕ ☐ Ship it✕ 2 left HTMLform · ul · button CSSvars · flex · states JSevents · array · render localStorage 1 user types + submits → push to the todos array 2 click ✕ or the checkbox → change the array 3 every change → save() to localStorage → render() 4 reload the page → load() reads it back. data → UI, always.
PLATE 15 — One small app that uses every chapter in this book.
Chapter 15 · How it all comes together

Build a to-do app that remembers

  1. HTML: semantic page with a labeled form and an empty list (2–5).
  2. CSS: variables, a centered card, flex rows, a .done state (6–10).
  3. JS state: one array of todo objects is the source of truth (11–12).
  4. Events: submit adds, delegated clicks toggle and delete (13).
  5. Persist: save to localStorage on every change, load on start.
index.html
<main class="card">
  <h1>My Tasks</h1>
  <form id="add">
    <label for="text" class="sr-only">New task</label>
    <input id="text" placeholder="What needs doing?" required>
    <button>Add</button>
  </form>
  <ul id="list"></ul>
  <p id="count" aria-live="polite"></p>
</main>
style.css
:root { --brand: #2F5BEA; --bg: #EAF0F2; --card: #fff; }
body  { background: var(--bg); font-family: system-ui; display: grid;
        place-items: start center; padding: 2rem 1rem; }
.card { background: var(--card); width: min(100%, 28rem); padding: 1.5rem;
        border-radius: 12px; box-shadow: 0 6px 20px rgb(0 0 0 / .08); }
form  { display: flex; gap: .5rem; } form input { flex: 1; }
li    { display: flex; align-items: center; gap: .5rem; padding: .5rem 0; }
li.done span { text-decoration: line-through; opacity: .5; }
li button { margin-left: auto; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
app.js
const KEY = "todos";
let todos = load();

function load() {
  try { return JSON.parse(localStorage.getItem(KEY)) ?? []; }
  catch { return []; }
}
function save() { localStorage.setItem(KEY, JSON.stringify(todos)); }

function render() {
  const list = document.querySelector("#list");
  list.replaceChildren(...todos.map(t => {
    const li = document.createElement("li");
    li.dataset.id = t.id;
    li.classList.toggle("done", t.done);
    const box = Object.assign(document.createElement("input"),
      { type: "checkbox", checked: t.done });
    const span = Object.assign(document.createElement("span"), { textContent: t.text });
    const del = Object.assign(document.createElement("button"), { textContent: "✕" });
    del.setAttribute("aria-label", `Delete ${t.text}`);
    li.append(box, span, del);
    return li;
  }));
  const left = todos.filter(t => !t.done).length;
  document.querySelector("#count").textContent = `${left} left`;
}

function update(next) { todos = next; save(); render(); }

document.querySelector("#add").addEventListener("submit", e => {
  e.preventDefault();
  const input = e.target.querySelector("input");
  update([...todos, { id: crypto.randomUUID(), text: input.value.trim(), done: false }]);
  input.value = "";
});

document.querySelector("#list").addEventListener("click", e => {
  const id = e.target.closest("li")?.dataset.id;
  if (!id) return;
  if (e.target.matches("button")) update(todos.filter(t => t.id !== id));
  if (e.target.matches("input")) update(todos.map(t =>
    t.id === id ? { ...t, done: !t.done } : t));
});

render();
The cheat sentence

"HTML says what things are, CSS says how they look on every screen, and JavaScript keeps the data, listens for events, and re-renders the DOM from that data."