← Teacher guides

Teacher guide: The DOM and the browser console

Make a real web page react with JavaScript: find elements, change them, listen for clicks and typing, and keep a list and a score, ending in a quiz page you build.

Open the student course · How the ideas build

Each lesson works two ways. Students can work through the online tutorial at their own pace (it checks their answers and saves their progress in their browser), or you can teach it to the whole class from the slides, then send students into the tutorial for the Modify and Make steps.

Every lesson guide has plain-language notes, the answers to every check, a solution for every task, and slides and a worksheet for Waypoints Prepare. These guide pages are not linked from student pages, but they are not secret either: keep printed Teacher editions for answers you do not want students to find.

Strategies for getting unstuck: Say what it should do, Test a small piece, Read the error, Trace it. A student who is stuck can try one before asking for a hint. The optional course How you learn best introduces them, and a few lesson decks have a short teach, show or nudge slide for one. (Each lesson page links to the cards from its first hint.)

Whole-course cheat sheet: Open to print (every command, grouped by unit: a handout for the final challenge)

Change the page

Find an element, change it, and run code when someone clicks.

Changing a page in 5 minutes (read before teaching this unit)

The idea in plain words

A web page is a tree of elements (the DOM). JavaScript can find an element with document.querySelector("#id") (a # for an id, a . for a class, a plain word for a tag), then change it: title.textContent = "…" for its words, title.style.color = "…" for its look. A script runs as soon as the browser reaches it, so it sits below the elements it uses. To wait for a click, hand the button a function: button.addEventListener("click", start). No brackets after start: that would run it now. console.log(…) writes messages in the Console under the page, to see what the code is doing.

Why programmers use it

  • Every interactive page is this: find an element, listen for an event, change something.
  • The Console shows what the code sees without changing the page.

An everyday picture, and where it breaks

A doorbell wired to a light: the button is the element, the click is the event, and the wiring is the handler. It breaks because you can wire any button to any change, and you can wire many handlers to one button.

Try it yourself (5 minutes)

  1. Run the first page and change the heading's text in the script.
  2. Mistype the selector. What does the Console say, and what does null mean?
  3. Add a second button that changes the heading back.

Questions students ask

  • Why does it say null? The selector found nothing. Check the spelling, and the # or the dot.
  • Why does nothing happen when I click? Check there are no brackets after the function in addEventListener.
  • Why does the script go at the bottom? It runs when reached, so the elements must be above it.

How it connects

This is the events lesson from Python and mousePressed from p5.js, with the page as the thing to change. The HTML & CSS lesson "Make it react" is a short version of this unit.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Building blocks

Classes, inputs, lists of elements and a score the page remembers.

Classes, inputs and lists in 5 minutes (read before teaching this unit)

The idea in plain words

Four tools for real pages. Classes: the look lives in CSS (.dark { … }) and JavaScript only flips it, with classList.toggle("dark") (no dot in the name). Inputs: box.value is the text typed in a box, and the "input" event fires on every keystroke; the value is always text, so Number(box.value) turns it into a number. Lists of elements: document.createElement("li") makes one, list.append(li) puts it on the page, li.remove() takes it off; an array in the script is data, and the page changes only when elements are made or removed. State: a variable made above the handler keeps its value from click to click; the page is only a picture of it.

Why programmers use it

  • Classes keep the look in CSS and the logic in JavaScript, so each is easy to change.
  • Data in variables, picture on the page is how every app works.
  • Making elements from data is how feeds, baskets and chats are built.

An everyday picture, and where it breaks

A whiteboard and a notebook: the notebook (variables) is the memory, and the whiteboard (the page) shows what is in it. It breaks because the page does not update itself when the notebook changes: your code has to rewrite the whiteboard.

Try it yourself (5 minutes)

  1. Add a CSS class to the night-mode page and a button that toggles it.
  2. Make two number boxes add up correctly, not as text.
  3. Make the list remove an item when it is clicked.

Questions students ask

  • Why does 4 + 5 give 45? Values from boxes are text. Use Number(...).
  • Why does my count go back to 1? The variable is made inside the handler, so it starts over each click.
  • Why is the new item not on the page? It was made but not appended, or it was only pushed to an array.

How it connects

Arrays and loops come from the p5.js course, variables and events from earlier units. The unit ends with the pieces needed for the quiz.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Final challenge: a quiz page

Build a quiz that checks answers and keeps score. Two optional lessons show the real browser console and loading data with fetch.

A quiz page in 5 minutes (read before teaching this unit)

The idea in plain words

A quiz page is data and a little memory. The data is an array of question objects ({ text, choices, answer }). The memory is two variables: current, which question is on the screen, and score. Showing a question makes a button for each choice with createElement. A click calls check(choice), which compares the choice with the answer using === (three equals signs: one = would change the variable and always be true), changes the score, moves on, and shows the next question or the end. Everything on the page is a picture of the data and those two variables.

Why programmers use it

  • Data-driven pages: one more object in the array gives one more question, with no new code.
  • Small state, simple code: only the things that change are variables.
  • Playtesting shows what a quiz does to a real person.

An everyday picture, and where it breaks

A teacher with a stack of cards: the next card is questions[current], and a tally on paper is the score. It breaks because the page forgets everything when it is closed; remembering needs somewhere to store it.

Try it yourself (5 minutes)

  1. Add a fourth question to the array.
  2. Make right answers green and wrong answers red.
  3. Show "You scored 2 of 3" at the end.

Questions students ask

  • Why does every answer say Correct? The check uses = instead of ===.
  • Why do the buttons pile up? Empty the choices box before making new buttons.
  • Can I keep the scores? Not on this page: it forgets when closed. A server or the browser's storage can keep them.

How it connects

This is the Catch the turtle, Catch the circle and Power-ups challenges as a web page. The optional lesson shows the real browser Console.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Open projects

Self-paced briefs students can pick up (after the lesson named on each, where one is named). Students tick their own milestones and claim a badge; the page lights the skills their code uses. Badges stay in the student's browser: ask them to press Show your teacher. Open the projects page

Light, dark and big text (after dom-style; JavaScript finding an element (querySelector, getElementById), JavaScript events (addEventListener), classList (add, remove, toggle))

Give a page you've made buttons that change how it looks: a dark mode and big text, and one look of your own. Each button switches its look on, and pressing it again switches it back.

Milestones:

  • Each button changes something you can see.
    1. Write the look as a CSS class first. Then the button only has to add that class to the page.
    2. A click handler can call classList.toggle with the class name.
    Students can earn this piece (reveal on): document.querySelector("#dark").addEventListener("click", () => {
    page.classList.toggle("dark");
    });
  • Pressing a button again switches its look back off.
    1. add only turns a class on. Look for the classList method that turns it on and off.
  • The page still reads well in every look, and with two looks on at once.
    1. Turn both looks on together and read the page. Can you still see the words?
    2. If one look sets a colour that clashes with another, change one of the two classes.

A student can paste in a page from the HTML & CSS courses or start from a heading and a paragraph. The idea is the one from Classes and themes: CSS holds the looks as classes, and JavaScript only adds and removes them. Watch for students setting style. properties one by one; point them back to classList.toggle.

One possible solution
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: sans-serif; padding: 16px; background: white; color: #222; }
  .dark { background: #1d2430; color: #f3f1ec; }
  .big { font-size: 22px; }
  button { margin-right: 6px; padding: 6px 12px; }
</style>
</head>
<body>
  <h1>My bike club</h1>
  <p>We ride every Saturday morning, rain or shine.</p>
  <button id="dark">Dark</button>
  <button id="big">Big text</button>

  <script>
    const page = document.querySelector("body");
    document.querySelector("#dark").addEventListener("click", () => {
      page.classList.toggle("dark");
    });
    document.querySelector("#big").addEventListener("click", () => {
      page.classList.toggle("big");
    });
  </script>
</body>
</html>
Flashcards (after dom-list; reading an input (.value), making an element (createElement), classList (add, remove, toggle))

Make flashcards for something you're learning: type a question and its answer, add it as a card, then click a card to flip it over.

Milestones:

  • Adding makes a new card on the page.
    1. Read what is in the two boxes with .value, then make a new element for the card.
    2. A new element is not on the page until you append it to a tag that is.
    Students can earn this piece (reveal on): const card = document.createElement("div");
    card.className = "card";
  • Clicking a card shows its answer, and clicking again shows the question.
    1. Put both the question and the answer in the card, and hide one of them with CSS.
    2. A class on the card can decide which one is hidden. Toggle it on click.
    Students can earn this piece (reveal on): card.addEventListener("click", () => card.classList.toggle("flipped"));
  • An empty box adds nothing.
    1. Check the boxes before you make the card. If either one is empty, stop.
    Students can earn this piece (reveal on): if (q === "" || a === "") return;

Builds on Building a list (making an element and adding it to the page) and Classes and themes (toggling a class for the flip). The flip is all CSS: two paragraphs in a card, and the flipped class hides one and shows the other.

One possible solution
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: sans-serif; padding: 16px; }
  .card { border: 2px solid teal; border-radius: 8px; padding: 14px; margin: 8px 0; cursor: pointer; }
  .card .answer { display: none; color: teal; }
  .card.flipped .question { display: none; }
  .card.flipped .answer { display: block; }
</style>
</head>
<body>
  <h1>Flashcards</h1>
  <p><input id="q" placeholder="Question"> <input id="a" placeholder="Answer"> <button id="add">Add card</button></p>
  <div id="cards"></div>

  <script>
    document.querySelector("#add").addEventListener("click", () => {
      const q = document.querySelector("#q").value;
      const a = document.querySelector("#a").value;
      if (q === "" || a === "") return;
      const card = document.createElement("div");
      card.className = "card";
      card.innerHTML = `<p class="question">${q}</p><p class="answer">${a}</p>`;
      card.addEventListener("click", () => card.classList.toggle("flipped"));
      document.querySelector("#cards").append(card);
    });
  </script>
</body>
</html>
Pick your own path (after dom-state; JavaScript finding an element (querySelector, getElementById), JavaScript events (addEventListener), changing text (textContent))

Write a short story where the reader picks what happens next. Two buttons, and the words change with every choice.

Milestones:

  • My story has at least three places to be.
    1. Plan on paper first: a box for each place and an arrow for each choice.
    2. A variable can hold which place the reader is in, as a word.
    Students can earn this piece (reveal on): let place = "start";
    const words = document.querySelector("#words");
  • One ending can be reached two different ways.
    1. Two different places can both send the reader to the same next place.
    2. In the click handler, check where the reader is now, then set where they go next.
  • A Start again button takes the reader back to the beginning.
    1. On an ending, a button can set the place back to the first one.
    Students can earn this piece (reveal on): else place = "start";

The variable that remembers where the reader is (place) is the score variable from A page that keeps score, now holding a word. Students who plan on paper first (boxes for places, arrows for choices) finish faster; the planning is the computational thinking here.

One possible solution
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: sans-serif; padding: 16px; max-width: 520px; }
  button { margin: 4px 6px 0 0; padding: 6px 12px; }
</style>
</head>
<body>
  <h1>The lost dog</h1>
  <p id="words">A dog runs past the gate with no collar. Do you follow it, or tell someone?</p>
  <button id="one">Follow it</button>
  <button id="two">Tell someone</button>

  <script>
    let place = "start";
    const words = document.querySelector("#words");
    const one = document.querySelector("#one");
    const two = document.querySelector("#two");

    function show() {
      if (place === "start") { words.textContent = "A dog runs past the gate with no collar. Do you follow it, or tell someone?"; one.textContent = "Follow it"; two.textContent = "Tell someone"; }
      if (place === "park") { words.textContent = "It stops at the park and sniffs a bench. A girl is calling a name."; one.textContent = "Call the same name"; two.textContent = "Go home"; }
      if (place === "neighbour") { words.textContent = "Your neighbour says the girl from the park lost her dog this morning."; one.textContent = "Go to the park"; two.textContent = "Go home"; }
      if (place === "found") { words.textContent = "The dog runs to the girl. She hugs it and thanks you. The end."; one.textContent = "Start again"; two.textContent = "Start again"; }
      if (place === "home") { words.textContent = "You go home and wonder about the dog all night. The end."; one.textContent = "Start again"; two.textContent = "Start again"; }
    }

    one.addEventListener("click", () => {
      if (place === "start") place = "park";
      else if (place === "park" || place === "neighbour") place = "found";
      else place = "start";
      show();
    });
    two.addEventListener("click", () => {
      if (place === "start") place = "neighbour";
      else if (place === "park" || place === "neighbour") place = "home";
      else place = "start";
      show();
    });
  </script>
</body>
</html>
A habit tracker that remembers (after dom-save; saving between visits (localStorage), making an element (createElement), JSON (response.json(), JSON.parse))

Make a habit tracker: tick off a habit when you've done it, and your ticks are still there next time the page opens.

Milestones:

  • Clicking a habit ticks it, and clicking again unticks it.
    1. Keep a list of the habits that are ticked.
    2. On a click, if the habit is in the list take it out, and if not put it in.
    Students can earn this piece (reveal on): if (ticks.includes(h)) ticks = ticks.filter((t) => t !== h);
    else ticks.push(h);
  • The ticks are still there after I run the page again.
    1. localStorage keeps text between visits. A list needs turning into text first.
    2. Save the list every time it changes, and read it back when the page starts.
    Students can earn this piece (reveal on): localStorage.setItem("ticks", JSON.stringify(ticks));
  • A Clear button starts fresh.
    1. Empty the list, save the empty list, then show the page again.

In the playground, "next time the page opens" means pressing Run again: the preview keeps each page's saved data as a stand-in for the browser's own storage. A downloaded copy opened in a real browser keeps its ticks for real. The list is saved as JSON, as in Saving between visits.

One possible solution
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: sans-serif; padding: 16px; }
  li { margin: 6px 0; }
  .done { text-decoration: line-through; color: gray; }
</style>
</head>
<body>
  <h1>My habits</h1>
  <ul id="list"></ul>
  <button id="clear">Clear</button>

  <script>
    const habits = ["Drink water", "Read for 20 minutes", "Walk the dog"];
    let ticks = [];
    try { ticks = JSON.parse(localStorage.getItem("ticks")) || []; } catch (e) { ticks = []; }

    function show() {
      const list = document.querySelector("#list");
      list.innerHTML = "";
      for (const h of habits) {
        const item = document.createElement("li");
        item.textContent = h;
        if (ticks.includes(h)) item.className = "done";
        item.addEventListener("click", () => {
          if (ticks.includes(h)) ticks = ticks.filter((t) => t !== h);
          else ticks.push(h);
          localStorage.setItem("ticks", JSON.stringify(ticks));
          show();
        });
        list.append(item);
      }
    }

    document.querySelector("#clear").addEventListener("click", () => {
      ticks = [];
      localStorage.setItem("ticks", JSON.stringify(ticks));
      show();
    });
    show();
  </script>
</body>
</html>