Browser JavaScript, DOM, Events, and Web APIs
Understand how JavaScript interacts with the browser through the DOM, event propagation, storage, networking, and other host APIs.
The DOM as a Tree
The Document Object Model represents an HTML document as a tree of nodes. JavaScript can query and modify this structure. DOM manipulation is host functionality supplied by browsers; it is not part of ECMAScript itself.
Efficient DOM work often means minimizing unnecessary layout, style recalculation, and rendering work rather than simply minimizing JavaScript statements.
const heading = document.querySelector('h1');
if (heading) {
heading.textContent = 'JavaScript';
}querySelector returns the first matching element. textContent updates its text without interpreting the value as HTML.
The DOM is a browser-provided representation of the document.
JavaScript can query and mutate DOM nodes.
textContent is generally safer than innerHTML for plain text.
Is the DOM part of the ECMAScript language specification?
Event Capturing, Targeting, and Bubbling
DOM events propagate through phases. During capture, the event travels from ancestors toward the target. The target phase occurs at the target. During bubbling, the event travels back outward through ancestors.
Event delegation uses bubbling to attach a listener to a stable ancestor rather than creating listeners for every child.
document.querySelector('#list').addEventListener('click', event => {
const item = event.target.closest('[data-id]');
if (!item) return;
console.log(item.dataset.id);
});One listener on the list handles clicks from dynamically created child elements by examining the event target.
Events have capture and bubble phases.
Event delegation can reduce listener count.
event.target identifies the originating target while currentTarget identifies the listener's element.
What is a major benefit of event delegation?
fetch and AbortController
fetch() provides a Promise-based interface for HTTP requests. It resolves when a response is available, including many HTTP error status codes; a 404 or 500 does not automatically reject the Promise. Applications should inspect response.ok or status explicitly.
AbortController can cancel fetch operations and other APIs that support AbortSignal.
const controller = new AbortController();
async function load() {
const response = await fetch('/api/users', {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
load().catch(console.error);
// Cancel when appropriate
controller.abort();The AbortSignal connects the controller to fetch. Aborting causes the request Promise to reject with an abort-related error.
fetch does not reject merely because the HTTP status is 4xx or 5xx.
Check response.ok or response.status.
AbortController provides cooperative cancellation for supported APIs.
Does fetch reject its Promise automatically for a 404 response?
localStorage and sessionStorage
Web Storage provides simple string key-value storage. localStorage persists across browser sessions for an origin, while sessionStorage is scoped to the browser page session. Values are strings, so objects require serialization with JSON.
Storage is synchronous, so large or frequent operations can affect responsiveness. It should not be treated as a secure secret store.
const settings = {
theme: 'dark',
compact: true
};
localStorage.setItem('settings', JSON.stringify(settings));
const restored = JSON.parse(
localStorage.getItem('settings') ?? '{}'
);
console.log(restored);Web Storage stores strings. JSON serialization converts the object into a string and JSON.parse restores the object structure.
Web Storage stores strings.
localStorage persists across sessions for the origin.
Do not store highly sensitive secrets in Web Storage merely because it is convenient.
What type of value does localStorage fundamentally store?