JavaScript in the Page: the DOM, querySelector and Events
Find, listen, change: one sign-up page traced through the DOM tree, querySelector, input and submit events, preventDefault, textContent, classList and append. Then the bug that explains why React exists.
What you will learn
- Explain the DOM as a tree of element objects built from the HTML
- Find elements with querySelector and know why a module script finds them
- Listen for input and submit events and stop a form's reload with preventDefault
- Change the page with textContent, classList, createElement and append
Before you start
- HTML forms
- JavaScript syntax: const, arrow functions, template strings
How does a script make a web page react when you type or click? The whole answer fits in three words: find, listen and change. We'll follow one small sign-up page through all three.
A page that does nothing
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign up</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="app.js"></script>
</head>
<body>
<h1>Join the course</h1>
<form id="signup">
<input id="name" name="name" placeholder="Name">
<input id="email" name="email" placeholder="Email">
<button>Join</button>
</form>
<p id="message"></p>
<ul id="members"></ul>
<p id="count">0 joined</p>
</body>
</html>
The page shows a heading, a Name field, an Email field, a blue Join button and "0 joined". Picture it with the script switched off. Emma types her name and email and clicks Join. The page flashes and reloads, the address now ends in ?name=Emma&email=emma%40example.com, and both fields are empty again. That's the form's default job, sending the fields to an address, exactly as in HTML forms. HTML and CSS draw the page; nothing on it reacts to you.
The browser builds a tree
The browser doesn't keep your file as text. It reads every tag and builds a tree in memory:
index.html.At the top sits the document, then html with two children, head and body. The body holds five elements, and the form has its own three children. JavaScript never edits your HTML file. It reads and changes this tree inside the browser.
Why "object model"? Each tag became a real object. The empty paragraph is an HTMLParagraphElement with properties such as tagName ("P"), id ("message"), textContent (empty), className (empty) and parentElement (the body). The name field is an HTMLInputElement whose value is what's typed in it. You can set these properties as well as read them, and the page shows whatever they say.
Find: querySelector
Here's the whole script, app.js:
// app.js - a script finds, listens and changes
// 1. FIND: querySelector returns one element object
const form = document.querySelector('#signup');
const nameInput = document.querySelector('#name');
const message = document.querySelector('#message');
const members = document.querySelector('#members');
const count = document.querySelector('#count');
// 2. LISTEN: 'input' fires on every key typed
nameInput.addEventListener('input', (event) => {
const typed = event.target.value;
message.textContent = `Hi, ${typed}!`;
});
// 'submit' fires when the form is sent (Join)
form.addEventListener('submit', (event) => {
event.preventDefault(); // stop the reload
const name = nameInput.value;
// 3. CHANGE: text, a class, a brand new element
message.textContent = `Thanks, ${name}!`;
message.classList.add('ok');
const li = document.createElement('li');
li.textContent = name;
members.append(li);
const total = members.children.length;
count.textContent = `${total} joined`;
form.reset(); // empty both fields for the next one
});
document.querySelector('#message') takes a CSS selector. The browser walks the tree in document order and returns the first match, or null when nothing matches. Each variable now points at one element object.
A typo like '#mesage' doesn't fail at once. querySelector quietly returns null, and the page only stops when you use it: TypeError: Cannot set properties of null (setting 'textContent').
When does app.js run?
The browser reads index.html top to bottom and the tree grows as it reads. When it reaches the script tag on line 7, only six elements exist: html, head and the four tags in the head. A type="module" script doesn't run right away; it waits until the whole page has been read, so #signup is already in the tree.
A plain <script src="app.js"> in the head runs immediately, before the body exists. querySelector('#signup') returns null and the page stops with TypeError: Cannot read properties of null (reading 'addEventListener'). Typing afterwards changes nothing, because no listener was ever added.
Listen: the input event
nameInput.addEventListener('input', ...) doesn't run the function. It registers it with the browser, like leaving your number at a shop so they call you when the parcel arrives. When Emma presses E, the browser creates an event object whose type is "input" and whose target is the name field, and calls your function with it. event.target.value is "E", so the message becomes "Hi, E!".
Every key fires one more input event: "Hi, Em!", "Hi, Emm!", "Hi, Emma!". One key, one event, one call. You never call the function yourself.
Submit and preventDefault
When Emma clicks Join, the browser first fires a click on the button. Because the button sits inside a form, the click makes the form send itself, which is a different event, submit, with the form as its target. That's why the listener is on the form, not the button.
The form's default action is the reload we saw at the start. event.preventDefault() cancels it: no reload, the address doesn't change, and nothing typed is lost (event.defaultPrevented is now true). Now your code gets to answer instead.
Change: text, a class, a new element
message.textContent = `Thanks, ${name}!`sets a property, and the page follows straight away.message.classList.add('ok')changesclassNamefrom empty to "ok".style.cssalready has an.okrule, green and bold, so the text turns green: the computed colour isrgb(0, 128, 0). You never told the page to redraw; the browser does it by itself. The class only switches on a rule the stylesheet already has.document.createElement('li')makes a new element in memory. It isn't in the tree yet, so it isn't on the page. Setting itstextContentand callingmembers.append(li)puts it into the tree, and Emma appears in the list.members.children.lengthcounts the list items, 1, and the counter becomes "1 joined".form.reset()empties both fields for the next person.
Liam signs up next, then Sofia. The browser calls the same handler each time: "Thanks, Liam!", 2 joined, then "Thanks, Sofia!", 3 joined, with three names in the list.
Every update by hand
Now count. One sign-up makes five separate changes: the message text, the class, the new list item, the counter and the reset. Each is a line you write by hand.
Forget just one. With the count line missing, three people sign up, the list shows Emma, Liam and Sofia, and the counter still says "0 joined". There's no error. The page simply disagrees with itself, and on a big page this kind of drift happens all the time. Keeping the page in step with your data automatically is exactly the job libraries such as React take on.
Quick recap
| Step | API | Remember |
|---|---|---|
| Find | document.querySelector(selector) | first match in the tree, or null |
| When | <script type="module"> | runs after the whole tree is built |
| Listen | el.addEventListener('input' | 'submit', fn) | the browser calls you with an event object |
| Stop the reload | event.preventDefault() | cancels the form's default action |
| Change | textContent, classList.add | set a property; the page redraws itself |
| Add | createElement + append | in memory first, on the page only after append |
Try it yourself
Add a check to the submit handler: if the name is empty, show "Please type a name" with a red .error class and don't add anything to the list. Then delete the counter line on purpose and watch the page disagree with itself.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
