The Academy

Loading the search index…

Searches the academy on this device only.

The DOM and events

Learn how the browser turns HTML into a tree that JavaScript can change, and use events such as clicks to make a page respond to the person using it.

35 minelementaryPractical task needs a laptop or desktop

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

By the end of this lesson you will be able to

  • Describe the DOM as a tree the browser builds from HTML.
  • Select an element with querySelector and change its text.
  • Add and remove a CSS class from JavaScript.
  • Attach an event listener so that a click runs a function.
  • Explain how HTML, CSS and JavaScript work together on one page.

A page that never changes is only a document. The pages you use every day react: a menu opens, a counter goes up, a message appears when you press a button. All of that happens because JavaScript can reach into the page and change it while it is on screen. To do this safely you need to know what the browser is actually holding in memory, and how it tells your code that something has happened.

What the DOM is

When the browser loads an HTML file it does not keep the text. It reads it and builds a live model of the page in memory, called the DOM (Document Object Model). Each element becomes an object, and because elements sit inside other elements, the objects form a tree. The html element is the root; head and body are its branches; headings, paragraphs and buttons are leaves. A good picture is a family tree: every element has a parent and may have children.

JavaScript does not edit your HTML file. It edits the DOM, and the browser redraws the screen to match. Refresh the page and the original HTML is loaded again, so changes made by a script are lost unless something saves them.

Diagram

A small page and the tree of elements the browser builds from it.

  • htmlRoot of the page
    • head
      • titleGarden club
    • body
      • h1 #titleHeading
      • p #messageParagraph
      • button #greetButton
A small page and the tree of elements the browser builds from it.
Read this figure as text

A tree with html at the top, head and body below, and a heading, paragraph and button inside body.

A tree. The root is html. It has two children: head and body. head contains title with the text Garden club. body contains three children: h1 with the id title, p with the id message, and button with the id greet. Every element is a node, and JavaScript can find any node by walking the tree or by asking for its id.

Selecting elements and changing them

To change an element you first need to select it. document.querySelector("...") takes a CSS selector, the same kind you wrote in the CSS lesson, and gives back the first matching element. Use #message for an id and .note for a class. Once you hold the element in a variable you can change its textContent (the plain text inside it), its style, its attributes and its classes.

JavaScript
const message = document.querySelector("#message");

message.textContent = "Welcome, Fatuma!";
message.classList.add("highlight");

// Later, to undo it:
// message.classList.remove("highlight");
Selecting an element and changing its text and class.

Changing a class is usually better than changing styles one by one from JavaScript. Keep the look in CSS, where the .highlight rule is written, and let JavaScript only switch the class on or off. That keeps the three languages tidy. Prefer textContent to innerHTML when you only want text: innerHTML reads its value as HTML, which becomes a security risk if the text came from a stranger.

Events: responding to the user

An event is something that happens on the page: a click, a key press, a form being submitted, the page finishing loading. The browser announces each one. Your code says in advance "when this event happens on this element, run this function". That function is an event listener (also called an event handler). You attach it with addEventListener, giving the event name and the function.

Diagram

What happens between a click and a change on screen.

  1. Step 1: User clicks
  2. Step 2: Click event created
  3. Step 3: Your listener found
  4. Step 4: Function changes DOM
  5. Step 5: Page redrawn
What happens between a click and a change on screen.
Read this figure as text

A flow of five steps from the user clicking a button to the page showing new text.

Five numbered steps. 1: the user clicks the Greet button. 2: the browser creates a click event for that button. 3: the browser finds the function you attached with addEventListener. 4: your function runs and changes the DOM, for example by setting new text. 5: the browser redraws the page and the user sees the change.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Garden club</title>
  <style>
    .highlight { background: #fff3cd; padding: 8px; }
  </style>
</head>
<body>
  <h1 id="title">Garden club</h1>
  <p id="message">Press the button.</p>
  <button id="greet">Greet</button>

  <script>
    const message = document.querySelector("#message");
    const button = document.querySelector("#greet");
    let clicks = 0;

    function handleClick() {
      clicks = clicks + 1;
      message.textContent = "Hello! You have clicked " + clicks + " times.";
      message.classList.add("highlight");
    }

    button.addEventListener("click", handleClick);
  </script>
</body>
</html>
A complete page: clicking the button changes the message and counts clicks. Save as index.html.

Notice handleClick has no brackets inside addEventListener. You are handing the function over to be called later, not calling it now. Writing handleClick() there would run it immediately, once, when the page loads.

Run the page and watch the DOM change

  1. Step 1: Save and open

    Save the page as index.html and open it in your browser.

    You should see: You see the heading Garden club, the text Press the button and a Greet button.

  2. Step 2: Click once

    Press the Greet button.

    You should see: The text changes to Hello! You have clicked 1 times, with a pale yellow background.

  3. Step 3: Click again

    Press it three more times.

    You should see: The number rises to 4. The variable clicks remembered its value between clicks.

  4. Step 4: Refresh

    Press F5.

    You should see: The page returns to Press the button, because the HTML file was loaded again and the DOM was rebuilt.

How HTML, CSS and JavaScript fit together

Each language has one job. HTML says what is on the page, CSS says how it looks, and JavaScript says what it does. They meet in the DOM: the browser builds the tree from HTML, attaches the CSS rules to its elements, and lets JavaScript change both the tree and the classes that CSS reacts to. Keep the jobs separate and your pages stay easy to fix.

Diagram

Three languages, three jobs, one page.

HTMLWhat is there
  • Headings, text, buttons
  • button id=greet
  • The skeleton
CSSHow it looks
  • Colours, fonts, spacing
  • .highlight { background: ... }
  • The clothes
JavaScriptWhat it does
  • Reacts to clicks and keys
  • Adds class highlight on click
  • The muscles
Three languages, three jobs, one page.
Read this figure as text

Three columns for HTML, CSS and JavaScript, each with its job and an example.

Three columns. HTML: structure and content; example, a button element with the id greet. CSS: appearance; example, a rule .highlight that gives a pale yellow background. JavaScript: behaviour; example, a listener that adds the class highlight when the button is clicked. Together, the browser combines all three in the DOM and draws the result.

Common mistakes

  • ✖ Instead of: Writing addEventListener("click", handleClick()) with brackets.

    ✔ Do this: Pass the function without brackets so it runs on each click, not once at load.

  • ✖ Instead of: Using innerHTML for plain text, especially text typed by a user.

    ✔ Do this: Use textContent for text. It shows characters as text and never runs them as HTML.

  • ✖ Instead of: Setting many style properties from JavaScript.

    ✔ Do this: Write a CSS class and add or remove it with classList.

  • ✖ Instead of: Using the same id on several elements.

    ✔ Do this: An id must be unique. Use a class for repeated elements and querySelectorAll to select them all.

If something goes wrong

Clicking the button does nothing.
Open the console with F12. A red error such as Cannot read properties of null means the selector found nothing. Check the id spelling, the # in the selector and where the script sits.
My change appears and then disappears.
You probably refreshed the page, or a form reloaded it. The DOM is rebuilt from the HTML file each time.
The class is added but nothing changes visually.
Check the CSS rule name has a full stop (.highlight) and is spelt the same as in the script, and that a more specific rule is not overriding it.
The browser shows the page as plain text with my code visible.
The file was probably saved as .txt. Save it again with the name ending in .html.

Key terms

DOM
The browser's live, tree-shaped model of a web page, which JavaScript can read and change.
Event listener
A function that the browser runs when something happens on the page, such as a click.
HTML tag
A word inside angle brackets that marks the start or end of an HTML element.
CSS selector
The part of a CSS rule that says which elements the rule applies to.

Practise it for real

Reading is not the same as being able to do it. Complete these on your own computer, then tick only what you have actually done. These ticks are your own honest record: nothing checks them for you.

Guided exerciseNeeds a laptop or desktop

Run and modify the click counter

Save the full example page and open it. Change the button text to Say hello, change the message wording, and make the count go up by 2 per click. Refresh after each edit.

You have succeeded when:
Independent challengeNeeds a laptop or desktop

Challenge: a dark mode button

Add a second button called Dark mode. Write a CSS rule .dark that gives the body a dark background and light text. Use classList.toggle("dark") on document.body when the button is clicked. Pressing it a second time should return the page to normal.

You have succeeded when:

Knowledge check

6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.

  1. Question 1.What is the DOM?
  2. Question 2.When JavaScript changes a paragraph's text, the HTML file on your computer is rewritten.
  3. Question 3.Amina puts her script in the head. The console says Cannot read properties of null (reading 'addEventListener'), although her button has the right id.What is the most likely cause?
  4. Question 4.Which line correctly runs handleClick each time the button is clicked?
  5. Question 5.Match each language to its job.
  6. Question 6.Put these in the order they happen when someone clicks a button with a listener.
    1. The user clicks
    2. The browser redraws the page
    3. The browser creates a click event
    4. Your function runs

Summary

  • The browser builds the DOM, a tree of element objects, from your HTML.
  • querySelector with a CSS selector finds an element; textContent and classList change it.
  • An event listener is a function run when an event such as a click happens.
  • Pass the function to addEventListener without brackets.
  • HTML gives structure, CSS gives looks, JavaScript gives behaviour; the DOM joins them.

Checklist: can you do these?

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

Related lessons

References and further reading

Official sources for details that can change between versions.

On this page