Sub topic 3
What the Browser Gives You: DOM and Web APIs
This chapter assumes you can write basic JavaScript functions and objects, read simple HTML, and load a script into a page with a module script, as covered in the previous chapter.
The JavaScript language defines arrays, promises, and classes. It does not define pages, buttons, or network requests. Those come from the browser, which adds host APIs to the global scope before your code runs. A host API is a feature that the runtime provides and the engine does not. Browser host APIs fall into two groups: the DOM and the wider set of Web APIs.
The working model
The DOM (Document Object Model) is a live tree of objects that represents the parsed HTML. Every tag becomes an element node that you can read, change, or remove. When you change the tree, the browser updates the page on screen.
Web APIs are everything else the browser exposes: fetch for HTTP, setTimeout for timers, localStorage for persistent key-value data, URL for parsing addresses, navigator for information about the browser, and many more. They are standardized by WHATWG and W3C, which is why they behave the same way in Chrome, Firefox, and Safari.
A worked example
This page counts clicks and remembers the total across reloads.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Counter</title>
<script type="module" src="counter.js"></script>
</head>
<body>
<button id="inc">Click me</button>
<p id="count"></p>
</body>
</html>// counter.js
const button = document.getElementById('inc');
const output = document.getElementById('count');
let count = Number(localStorage.getItem('count') ?? 0);
render();
button.addEventListener('click', () => {
count += 1;
localStorage.setItem('count', String(count));
render();
});
function render() {
output.textContent = `Clicked ${count} times`;
}This script uses several host APIs. document.getElementById reads from the DOM tree, and addEventListener registers a callback that the browser calls when the event fires. textContent writes into the tree. localStorage is a Web API that keeps string data for the page's origin.
The most common DOM operations are:
| Task | API |
|---|---|
| Find one element | `document.querySelector('.item')` |
| Find many elements | `document.querySelectorAll('li')` |
| Change text safely | `el.textContent = 'hi'` |
| Create and insert | `document.createElement('li')`, `parent.append(child)` |
| React to input | `el.addEventListener('input', fn)` |
| Toggle styling | `el.classList.toggle('active')` |
Common errors
nullfrom a query. If a classic script in the<head>runs before the body is parsed,getElementByIdreturnsnull, and the next property access throws aTypeError. You can fix this withtype="module"ordefer, or by placing the script at the end of the body.- Using
innerHTMLwith user input. Assigning untrusted strings toinnerHTMLruns any markup inside them, which opens the page to cross-site scripting. UsetextContentfor text. - Treating a NodeList as an array.
querySelectorAllreturns a NodeList. It hasforEachbut nomaporfilter. Convert it withArray.from(list)or[...list]. - Storing non-strings.
localStorageconverts every value to a string, sosetItem('n', {a: 1})stores"[object Object]". UseJSON.stringifyandJSON.parse. - Expecting these APIs in Node.js.
document,window, andlocalStoragedo not exist in Node.js. A later chapter shows how to detect the environment safely.
Exercise
A page runs localStorage.setItem('prefs', { theme: 'dark' }) and later localStorage.getItem('prefs').theme. What is the result, and how do you fix it?
Show answer
The result is undefined, because localStorage stored the string "[object Object]", and strings have no theme property. To fix it, store JSON.stringify({ theme: 'dark' }) and read the value back with JSON.parse(localStorage.getItem('prefs')).theme.
Exercise
A list's items are added after the page loads, and clicks on the new items do nothing. The code ran document.querySelectorAll('li').forEach(li => li.addEventListener('click', handle)) once at startup. Why, and what is a better approach?
Show answer
querySelectorAll returns only the elements that exist when it runs, so items added later never get a listener. Attach one listener to the parent ul and check event.target.closest('li') inside it. This is event delegation, and it covers items added at any time.