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.
- htmlRoot of the page
- head
- titleGarden club
- body
- h1 #titleHeading
- p #messageParagraph
- button #greetButton
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.
const message = document.querySelector("#message");
message.textContent = "Welcome, Fatuma!";
message.classList.add("highlight");
// Later, to undo it:
// message.classList.remove("highlight");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.
- Step 1: User clicks
- Step 2: Click event created
- Step 3: Your listener found
- Step 4: Function changes DOM
- Step 5: Page redrawn
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.
<!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>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
Step 1: Save and open
Save the page as
index.htmland open it in your browser.You should see: You see the heading Garden club, the text Press the button and a Greet button.
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.
Step 3: Click again
Press it three more times.
You should see: The number rises to 4. The variable
clicksremembered its value between clicks.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.
- Headings, text, buttons
- button id=greet
- The skeleton
- Colours, fonts, spacing
- .highlight { background: ... }
- The clothes
- Reacts to clicks and keys
- Adds class highlight on click
- The muscles
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
innerHTMLfor plain text, especially text typed by a user.✔ Do this: Use
textContentfor 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
querySelectorAllto 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 nullmeans 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.
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.
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.
Knowledge check
6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.
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.
- Introduction to the DOM (MDN Web Docs)
- Introduction to events (MDN Web Docs)