Home · Academy · Robotics & Coding · Web Fundamentals · The DOM and Interaction

The DOM and Interaction

Learn to select elements with the DOM, change text/style and add interaction with events.

LESSON COMPASS

What will you use this page for?

Core idea

The DOM is the map the browser keeps of your page as a tree; JavaScript can pick one element from that map, change its text, class or style, and listen for events such as a click.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Selecting an element before it exists If you put the <script> tag before the <body> content, JavaScript tries to select an element that does not exist yet and gets null . The fix: put the script right before the closing </body> tag, or run the code after the page has loaded. Mixing up id and selector You do not write…

Next connection

Forms and Data Safety: We will learn how forms that collect information from a user work, and why protecting personal data matters.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration30–45 min
PrerequisiteIntroduction to JavaScript
ContentStandard lesson · 1,576 words
Last updated

One-sentence summary

The DOM is the map the browser keeps of your page as a tree; JavaScript can pick one element from that map, change its text, class or style, and listen for events such as a click.

Why does it matter?

The HTML you have written so far just sat there. The page loaded, the text appeared, and it waited. But real websites talk back to you: you press a button and a menu opens; you type in a box and a result changes.

The name for this liveliness is interaction. What makes interaction possible is that JavaScript can reach into the page. It does not reach in through raw HTML, but through a structure called the DOM.

Understanding the DOM answers the question, “How do I change the thing I see on the screen?” Almost every line you write from here rests on one trio: find an element, listen for an event, and change something.

What is the DOM?

The DOM (Document Object Model) is a tree-shaped model the browser builds in memory after it reads your HTML page. Every HTML tag becomes a node in this tree.

Think about this small page:

<body>
  <h1>Hello</h1>
  <p>This is a paragraph.</p>
</body>

The browser keeps it as a tree like this:

body
├── h1  →  "Hello"
└── p   →  "This is a paragraph."

When JavaScript finds a node in this tree and changes it, the browser updates the screen right away. So the DOM is the bridge between your code and the page your eyes see.

Why don’t we edit the HTML directly?

The HTML file is read once and turned into the tree. While the page is running, we no longer change the file — we change this tree in memory. So when we say “change the text,” we really mean “change the content of a node in the tree.”

Selecting an element

Before we change something, we have to find it. The browser gives us ready-made commands for this.

Selecting with getElementById

If we give an element an id in HTML, we can call it by name. An id must be unique on a page.

<h1 id="title">Hello</h1>
const title = document.getElementById("title");
console.log(title.textContent); // "Hello"

document is the object that represents the whole page. getElementById tells it, “bring me the element with this id.”

Selecting with querySelector

querySelector uses the same selectors as CSS. That makes it very flexible: you can pass #id, .class or a plain tag name.

const title = document.querySelector("#title"); // by id
const para = document.querySelector("p");        // by tag
const card = document.querySelector(".card");    // by class

querySelector returns the first matching element. If nothing matches, it returns null; forgetting this case is a common mistake.

Changing an element

Once we have found an element, we can change its content, its class and its style.

Changing the text

The textContent property is the text inside an element. If we assign it a new value, the text changes instantly.

const title = document.querySelector("#title");
title.textContent = "Hello, world!";

Adding or removing a class

We prepare the look with CSS, then use JavaScript only to add and remove a class. This keeps style and behaviour cleanly separated.

.highlight {
  color: white;
  background-color: teal;
}
const card = document.querySelector(".card");
card.classList.add("highlight");    // add a class
card.classList.remove("highlight"); // remove a class
card.classList.toggle("highlight"); // remove if present, add if not

Changing the style directly

Sometimes we just want to change one property quickly. style does that. CSS’s background-color becomes backgroundColor in JavaScript.

const box = document.querySelector("#box");
box.style.backgroundColor = "orange";

For small changes style is handy; but if many properties will change, using a class is tidier.

Listening for events

An event is something that happens on the page: a click, a key press, a mouse moving over an element. JavaScript can listen for these events and run a function when the event happens.

For this we use addEventListener. We give it two things: which event to listen for and what to do.

<button id="button">Click me</button>
<p id="message">You haven’t clicked yet.</p>
const button = document.querySelector("#button");
const message = document.querySelector("#message");

button.addEventListener("click", function () {
  message.textContent = "Thanks, you clicked!";
});

Here "click" is the event being listened for. The function we pass second runs when the event happens. This is called an event handler.

Example 1: Change the text on click

The code above is a complete example: every time the button is pressed, the paragraph’s text changes. There is no need to reload the page; the change happens instantly.

Example 2: Change the colour on click

We can use the same idea for colour. Thanks to toggle, the same button switches on and off.

<button id="colorButton">Change colour</button>
<div id="box">I am a box.</div>
#box { padding: 20px; }
.dark { background-color: navy; color: white; }
const colorButton = document.querySelector("#colorButton");
const box = document.querySelector("#box");

colorButton.addEventListener("click", function () {
  box.classList.toggle("dark");
});

The first click darkens the box, the second returns it to normal. This is the simplest form of the “dark mode” button on real sites.

Mini practice

Let’s build a small counter. Every time the button is clicked, the number on the screen goes up by one.

Steps:

  1. Create a starting HTML file.
  2. Add a <button> and a <span> that shows the number.
  3. In JavaScript, create a let variable to hold the number.
  4. Add a click listener to the button.
  5. On each click, increase the variable and write it into the <span>.
<p>Counter: <span id="count">0</span></p>
<button id="increase">Increase</button>
let counter = 0;
const count = document.querySelector("#count");
const increase = document.querySelector("#increase");

increase.addEventListener("click", function () {
  counter = counter + 1;
  count.textContent = counter;
});

When it runs, you will see the number rise with every press. Changes I’d like you to try:

Common mistakes

Selecting an element before it exists

If you put the <script> tag before the <body> content, JavaScript tries to select an element that does not exist yet and gets null. The fix: put the script right before the closing </body> tag, or run the code after the page has loaded.

Mixing up id and selector

You do not write # inside getElementById("title"). But you do write # inside querySelector("#title"). The two follow different rules.

Using innerHTML just to change text

When you only need to change text, use textContent instead of innerHTML. Because innerHTML can run incoming text as HTML, it can open a security hole.

Writing add twice instead of toggle

If you want one button to switch on and off, using add and remove forces you to decide which one each time; classList.toggle does that job in a single line.

Safety note

Lesson summary

Check questions

  1. What does DOM stand for, and why does the browser build it?
  2. What is the writing difference between getElementById("box") and querySelector("#box")?
  3. Which property do we use to change the text inside an element?
  4. What does classList.toggle("active") do to an element?
  5. What are the two pieces of information we pass to addEventListener("click", ...)?

Answers

  1. DOM means Document Object Model. After the browser reads the HTML, it keeps it as a tree in memory, so JavaScript can find and change the page.
  2. getElementById takes only the id name ("box"). querySelector expects a CSS selector, so the id needs a # in front ("#box").
  3. We use the textContent property; when we assign it a new value, the text on the screen changes instantly.
  4. If the class is not on the element it adds it, and if it is there it removes it. This gives an on/off behaviour in a single call.
  5. The first is the name of the event to listen for (for example "click"), and the second is the function that runs when the event happens.

Source and verification note

For “The DOM and Interaction”, verification focuses on whether the relationship between What is the DOM? and Selecting an element remains consistent across examples. Examples use standards-oriented HTML, CSS and browser JavaScript. A page should be checked not only visually but also for keyboard use, focus order, mobile layout and meaningful heading structure.

Next lesson

Forms and Data Safety: We will learn how forms that collect information from a user work, and why protecting personal data matters.

Start QuizBack to Web Fundamentals
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.