Find a course

Module 5: Web Pages, Errors and Async CodeLesson 10 of 1213 min

Controlling a Web Page: the DOM and Events

Select page elements, change their text, classes and styles through the DOM, and respond to clicks and form input with event listeners.

Step 1 of 14Learn

How JavaScript sees a web page

When a browser loads an HTML page, it builds a tree of objects in memory called the DOM (Document Object Model). Every heading, paragraph, button and input becomes an object that JavaScript can read and change. Change the object, and the page on screen updates instantly, without reloading.

Take this HTML:

<h1 id="title">Welcome</h1>
<p class="note">You have 0 messages.</p>
<button id="refresh">Refresh</button>

To work with an element, first select it. The modern tools accept CSS selectors, the same ones used in stylesheets:

const title = document.querySelector("#title");   // by id
const note = document.querySelector(".note");     // first element with class note
const allNotes = document.querySelectorAll(".note"); // all matches (a list)

document is the object representing the whole page. querySelector returns the first match or null if nothing matches; querySelectorAll returns every match, which you can loop over with for...of or forEach. You will also see the older document.getElementById("title"), which does the same job for ids.

If you select an element in a script that runs before the HTML below it has loaded, you get null. That is why scripts are usually placed at the end of the body or loaded with the defer attribute: <script src="app.js" defer></script>.

Step 2 of 14Practice · Diagram

The DOM: your HTML as a tree of objects

Which node is the parent of the button?

Tap the shape that answers the question, then press Check.

The DOM: your HTML as a tree of objectsHierarchy diagram: document, html, head, body, title, h1#title, p.note, button#refresh.documenthtmlheadbodytitleh1#titlep.notebutton#refresh
document
html
head
body
title
h1#title

document.querySelector("#title")

p.note

document.querySelector(".note")

button#refresh

document.querySelector("#refresh")

Step 3 of 14Practice · Match the pairs

Match each selector to what document.querySelector would find.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. "#cart"
  2. ".price"
  3. "button"
  4. "form input"

Step 4 of 14Learn

Changing what the user sees

Once you have an element, you can change it through its properties:

title.textContent = "Welcome back, Sam!";   // replace the text
note.classList.add("highlight");            // add a CSS class
note.classList.remove("hidden");            // remove one
note.classList.toggle("open");              // add if missing, remove if present
title.style.color = "darkblue";             // set an inline style

textContent vs. innerHTML. textContent sets plain text. innerHTML parses its value as HTML, so el.innerHTML = "<b>Hi</b>" shows bold text. That power is also a danger: if you insert text typed by a user with innerHTML, a malicious user can inject a script. This attack is called cross-site scripting (XSS). Use textContent for anything that comes from users or other websites.

Adding new elements:

const item = document.createElement("li");
item.textContent = "Buy milk";
document.querySelector("#todo-list").append(item);

element.remove() deletes an element from the page.

Prefer changing classes over setting many inline styles. Keep the visual rules in CSS (.highlight { background: yellow; }) and let JavaScript just switch classes on and off. Your code stays shorter and the design stays in one place.

Step 5 of 14Compare

textContent versus innerHTML

AspecttextContentinnerHTML
Treats the value asPlain textHTML markup
el.x = "<b>Hi</b>" shows<b>Hi</b> literallyHi in bold
Safe for user input?YesNo: risk of script injection (XSS)
Use it forAlmost all text updatesTrusted markup you wrote yourself

Step 6 of 14Practice · What would you do?

What would you do?

A comment box on your site displays each new comment with list.innerHTML += "<li>" + commentText + "</li>";. A user posts a comment containing a <script> tag. What is the best fix?

Step 7 of 14Learn

Events: reacting to the user

Pages come alive when they respond to the user. The browser fires events for clicks, key presses, form submissions, scrolling and more. You attach a function, an event listener, that runs when the event happens:

const button = document.querySelector("#refresh");
let count = 0;

button.addEventListener("click", () => {
  count++;
  note.textContent = `You clicked ${count} times.`;
});

addEventListener(type, callback) takes the event name and a callback. Common event types: "click", "input" (fires on every change in a text field), "change", "submit", "keydown" and "DOMContentLoaded" (the HTML has finished loading).

The callback receives an event object with details about what happened:

const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
  event.preventDefault();               // stop the page from reloading
  const email = form.querySelector("input").value;
  console.log("Signing up", email);
});

event.preventDefault() cancels the browser's default action; for forms, that default is reloading the page, which would wipe out your JavaScript state. event.target is the element that triggered the event.

Remember that input values are always strings. Convert them with Number() before doing math, as you saw in the operators lesson.

Step 8 of 14Diagram

From a click to a changed page

From a click to a changed pageProcess diagram: User clicks the button → Browser fires "click" → Your listener runs → Update the data → Update the DOM.User clicks the buttonBrowser fires"click"Your listener runsUpdate the dataUpdate the DOM

Tap a shape with to see more.

User clicks the button
Browser fires "click"

It creates an event object describing what happened.

Your listener runs

The callback you passed to addEventListener.

Update the data

count++

Update the DOM

note.textContent = ...; the screen changes instantly, no reload.

Step 9 of 14Note

Step 10 of 14Practice · Put in order

Put these steps in order to make a button update a counter on the page.

Drag the items, or use the arrow buttons, to put them in order.

  1. Select the button and the counter element with querySelector
  2. Call addEventListener("click", ...) on the button
  3. Create a variable to hold the count
  4. Inside the callback, set the counter element's textContent
  5. Inside the callback, increase the count

Step 11 of 14Note

Step 12 of 14Practice · Select all that apply

A user types into a search box. Which statements are true? Select all that apply.

Select all that apply.

Step 13 of 14Note

Step 14 of 14Practice · Choose one

Your script runs document.querySelector("#menu").classList.add("open") and the console shows TypeError: Cannot read properties of null. What is the most likely cause?