Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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:

DOM tree: document, html, head with meta, title, link, script; body with h1, form#signup (input#name, input#email, button), p#message, ul#members, p#count. Fifteen elements. documenthtmlheadbody metatitlelinkscript h1form#signupp#messageul#membersp#count input#nameinput#emailbutton
The DOM, the Document Object Model: fifteen elements built from 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') changes className from empty to "ok". style.css already has an .ok rule, green and bold, so the text turns green: the computed colour is rgb(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 its textContent and calling members.append(li) puts it into the tree, and Emma appears in the list.
  • members.children.length counts 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

StepAPIRemember
Finddocument.querySelector(selector)first match in the tree, or null
When<script type="module">runs after the whole tree is built
Listenel.addEventListener('input' | 'submit', fn)the browser calls you with an event object
Stop the reloadevent.preventDefault()cancels the form's default action
ChangetextContent, classList.addset a property; the page redraws itself
AddcreateElement + appendin 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 12 of 59

Previous
Async JavaScript: Promises, async/await, fetch and Promise.all
Next post
npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page

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.

On this page

  • A page that does nothing
  • The browser builds a tree
  • Find: querySelector
  • When does app.js run?
  • Listen: the input event
  • Submit and preventDefault
  • Change: text, a class, a new element
  • Every update by hand
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.