Sub topic 3
What the Browser Gives You: DOM and Web APIs
A JavaScript engine such as V8 or SpiderMonkey knows the language: objects, functions, promises, Array.prototype.map. It does not know what a web page, a button, or an HTTP request is. The browser adds those through host APIs, objects and functions it places in the global scope before your script runs. This chapter covers the two groups you will use most: the DOM (Document Object Model), which represents the page, and the wider set of Web APIs, such as fetch, storage, timers, and URL handling.
This chapter assumes you can write basic JavaScript (functions, objects, arrays, arrow functions), know enough HTML to recognize elements and attributes, and can load a script into a page. The previous chapter covered script loading. All examples use <script type="module">, so they run after the document has been parsed.
Where Web APIs Come From
The ECMAScript specification defines the language. A separate set of documents, mostly maintained by WHATWG and W3C, defines Web APIs: the DOM Standard, the HTML Standard, the Fetch Standard, the URL Standard, and others. Browsers implement both sets. The engine runs your code, and when you call document.querySelector, the call goes into browser code written in C++ or Rust.
The split matters because some Web APIs have also been adopted by Node.js and others have not. The table below shows common APIs and where each one is available.
| API | Purpose | Defined by | Built into Node.js? |
|---|---|---|---|
| `document`, `Element`, `Node` | Read and change the page | DOM / HTML Standard | No |
| `addEventListener`, `EventTarget` | Subscribe to events | DOM Standard | `EventTarget` yes, page events no |
| `fetch`, `Request`, `Response` | HTTP requests | Fetch Standard | Yes, from Node.js 18 |
| `URL`, `URLSearchParams` | Parse and build URLs | URL Standard | Yes |
| `setTimeout`, `setInterval` | Timers | HTML Standard | Yes, though Node returns an object instead of a number |
| `localStorage`, `sessionStorage` | Key-value storage per origin | HTML Standard | Not by default |
| `AbortController` | Cancel async operations | DOM Standard | Yes |
| `structuredClone` | Deep-copy values | HTML Standard | Yes |
A later chapter on universal code builds on the "Yes" column. This chapter is about the browser side.
The DOM as a Tree of Nodes
When the browser parses HTML, it builds a tree of nodes. Every element, every run of text, and every comment becomes a node. The document object is the root, and document.documentElement is the <html> element.
Two distinctions trip people up:
- Nodes and elements are different.
childNodesincludes text nodes, which are often just the whitespace between tags.childrenincludes only elements. If you loop overchildNodesand expect only<li>elements, you will also get text nodes. - Attributes and properties are different.
input.getAttribute('value')returns the value written in the HTML.input.valuereturns what the user has typed now. Changing the property does not change the attribute.
Finding Elements
querySelector and querySelectorAll take any CSS selector. They are the methods to use by default.
const list = document.querySelector('#list'); // first match or null
const items = document.querySelectorAll('#list > li'); // static NodeList
console.log(items.length);
items.forEach((li) => console.log(li.textContent));querySelectorAll returns a static NodeList: a snapshot that stays the same when the page changes later. The older getElementsByClassName and getElementsByTagName return a live HTMLCollection, which updates as the DOM changes. If you remove elements from a live collection while you loop over it, you will skip items. A NodeList has forEach but not map or filter. Use Array.from(items) or [...items] when you need those.
Changing the Page
Create elements with document.createElement, set their content, and insert them with append, prepend, before, after, or replaceWith. Remove an element with element.remove().
const li = document.createElement('li');
li.textContent = 'Write the report';
li.classList.add('task');
li.dataset.id = '42'; // becomes data-id="42"
document.querySelector('#list').append(li);For text, use textContent. It treats the value as plain text, so a string like <img src=x onerror=alert(1)> shows up as literal characters. innerHTML parses its value as HTML. If any part of that string comes from a user, a URL, or an API response, you have built a cross-site scripting (XSS) hole. Use innerHTML only with markup you wrote yourself.
Events
The browser reports user actions and state changes as events. You subscribe with addEventListener(type, listener, options). The listener receives an Event object with type, target (the element where the event started), and currentTarget (the element whose listener is running).
Propagation: Capture, Target, Bubble
Most events travel in three phases. In the capture phase the event goes down from window to the target. In the target phase it reaches the target. In the bubble phase it goes back up. Listeners run in the bubble phase by default. Pass { capture: true } to run in the capture phase instead.
Bubbling makes event delegation possible. You put one listener on a parent and use event.target.closest(selector) to work out which child was hit. Delegation also handles children you add later, which a per-element listener would miss.
Some events do not bubble, among them focus, blur, mouseenter, and load on elements. Their bubbling equivalents focusin and focusout exist for delegation.
Useful Listener Options and Methods
| Feature | Effect |
|---|---|
| `{ once: true }` | Removes the listener after its first call |
| `{ passive: true }` | Promises not to call `preventDefault`, so scrolling stays smooth |
| `{ signal }` | Removes the listener when the `AbortController` is aborted |
| `event.preventDefault()` | Cancels the default action, such as following a link or submitting a form |
| `event.stopPropagation()` | Stops the event from reaching further elements |
removeEventListener only works if you pass the same function reference and the same capture value. Anonymous arrow functions cannot be removed that way. An AbortController signal is the simpler option.
Other Web APIs You Will Use Constantly
fetch
fetch returns a promise that resolves to a Response as soon as the headers arrive. The promise rejects only on network failure. A 404 or 500 status still resolves, so always check response.ok. Reading the body (response.json(), response.text()) is a second asynchronous step. In the browser, fetch also follows the same-origin policy: a request to another origin succeeds only if that server sends the right CORS headers. The security chapter covers this in more detail.
Storage
localStorage keeps strings per origin across sessions. sessionStorage keeps them per tab. Both are synchronous and store only strings, so you must serialize objects with JSON.stringify. Both can throw, for example when the quota is full or when storage is blocked in some private modes. Wrap writes in try/catch. For large or structured data, use IndexedDB, which is asynchronous.
URL and URLSearchParams
Do not parse URLs with string splitting.
const url = new URL('/search?q=dom&page=2', 'https://example.com');
console.log(url.searchParams.get('page')); // "2"
url.searchParams.set('q', 'web apis');
console.log(url.href); // https://example.com/search?q=web+apis&page=2A Complete Example
This page keeps a task list. It uses delegation, textContent, localStorage, and a form submit handler. Save both files in one folder and serve the folder over HTTP, for example with npx serve .. Module scripts do not load from file:// URLs.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tasks</title>
<script type="module" src="tasks.js"></script>
</head>
<body>
<h1>My tasks</h1>
<form id="add">
<input name="title" required placeholder="New task">
<button>Add</button>
</form>
<ul id="list"></ul>
</body>
</html>// tasks.js
const KEY = 'tasks';
const form = document.querySelector('#add');
const list = document.querySelector('#list');
function load() {
try {
return JSON.parse(localStorage.getItem(KEY)) ?? [];
} catch {
return [];
}
}
function save(tasks) {
try {
localStorage.setItem(KEY, JSON.stringify(tasks));
} catch (err) {
console.warn('Could not save tasks:', err);
}
}
let tasks = load();
function render() {
const fragment = document.createDocumentFragment();
for (const task of tasks) {
const li = document.createElement('li');
li.dataset.id = task.id;
li.textContent = task.title + ' ';
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'remove';
remove.textContent = 'Remove';
li.append(remove);
fragment.append(li);
}
list.replaceChildren(fragment);
}
form.addEventListener('submit', (event) => {
event.preventDefault();
const title = new FormData(form).get('title').trim();
if (!title) return;
tasks.push({ id: crypto.randomUUID(), title });
save(tasks);
form.reset();
render();
});
list.addEventListener('click', (event) => {
const button = event.target.closest('button.remove');
if (!button) return;
const id = button.closest('li').dataset.id;
tasks = tasks.filter((task) => task.id !== id);
save(tasks);
render();
});
render();A few details in this code are worth noting. crypto.randomUUID requires a secure context, which means HTTPS or localhost. replaceChildren clears the list and inserts the fragment in one call. One click listener on <ul> covers every Remove button, including buttons created after the listener was attached. Task titles go through textContent, so a title containing HTML is shown as text and never runs.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot read properties of null` | Element not yet parsed, or wrong selector | Use a module or `defer` script, and check the selector |
| `items.map is not a function` | `NodeList` is not an array | `Array.from(items).map(...)` |
| Form reloads the page | Default submit action | `event.preventDefault()` in the `submit` handler |
| Listener fires for new items only sometimes | Listeners attached per element before insertion | Use delegation on a stable parent |
| `fetch` "succeeds" on a 404 | `fetch` resolves for HTTP errors | Check `response.ok` |
| Stored object reads back as `"[object Object]"` | Storage accepts only strings | `JSON.stringify` / `JSON.parse` |
Exercise
You attach a click listener directly to each of three li elements, then add a fourth li with append. Clicking the fourth item does nothing. Explain why and describe a fix that needs only one listener.
Show answer
addEventListener binds to the specific elements that existed when it was called, so the fourth li has no listener. Put a single listener on the parent ul and, inside it, use event.target.closest('li') to find the clicked item. Clicks bubble from any li, including ones added later, up to the ul.
Exercise
A page shows a comment with list.innerHTML += <li>${comment}</li>, where comment comes from an API. Name two problems and rewrite it safely.
Show answer
First, it is an XSS risk because the comment is parsed as HTML and can run script through attributes such as onerror. Second, += reparses and rebuilds the whole list, which loses existing listeners on its children and costs time. Safe version: const li = document.createElement('li'); li.textContent = comment; list.append(li);
Exercise
Which of these work in plain Node.js 18 or later with no extra packages: fetch, document.querySelector, URLSearchParams, localStorage, AbortController?
Show answer
fetch, URLSearchParams, and AbortController work. document is not defined in Node.js, and localStorage is not available by default.