Chapter 6: The document object model API
Introduces the DOM as the browser’s in-memory document tree and explains why native APIs and careful updates are enough to build interfaces without a library.
After this chapter you will be able to
- DOM document tree. Explain that the DOM is an in-memory representation of the document used by the rendering engine to paint the page, with elements, text, and comments arranged as related nodes.
- Native DOM capabilities. Describe why a library is not required for basic DOM work: the browser platform already supplies selectors, node constructors, insertion and removal helpers, and events.
- DOM element objects. Explain that each document element is represented by an object with properties and methods, using HTMLElement or an interface that inherits from it.
- DOM updates and repaint timing. Distinguish a synchronous DOM update from the later browser repaint, and explain why the browser batches changes until the current JavaScript task finishes and the main thread is free.
- Element references and changes. Describe how to obtain an existing element by querying the document or create and insert a new one, then use an element reference to change the UI.
- Core DOM node types. Describe the roles of Document, Element, and Text nodes, and explain how parentNode and childNodes relate nodes in the tree.
- DOM changes and rendering. Explain how the DOM tree originates and how JavaScript mutations become visible.
- Shared and specialized element APIs. Explain that HTMLElement provides properties shared by most HTML elements, while concrete subclasses provide element-specific properties and methods that avoid string parsing.
- Class data and style management. Justify using classList and dataset rather than manipulating class and data attribute strings, and explain why CSS classes are generally preferred to inline styles.
- Window document and node roles. Describe how window, document, and objects representing elements or other nodes relate to a page: window is the browsing context’s global object, document represents the active document and hangs from window, and document nodes have objects that code can reference.
- Separate documents and access. Explain that iframes, popups, and in-memory documents each have their own document and node tree, and distinguish DOM access from communication across origins.
- Cross-document node ownership. Distinguish transferring a node with adoptNode() from cloning it with importNode() when working across documents.
- DOM query return types. Distinguish a query that returns one Element or null from one that returns a collection, and compare HTMLCollection with NodeList by contents and whether they update as the DOM changes.
- Live collections and snapshots. Explain the risk of changing matching elements while iterating a live collection and when to convert a DOM collection into an array.
- Intentional scoped selectors. Compare classic getters with CSS-selector queries, and explain how intentional selectors and container-scoped searches reduce coupling.
- DOM tree navigation. Explain how an HTMLElement can serve as a starting point for browsing parents, children, and siblings, and why browsing the DOM may encounter nodes other than HTML elements.
- Element-specific native APIs. Explain that HTML tags have corresponding interfaces whose properties, methods, and events provide behavior suited to each element. Give an example such as media playback, form values, details open state, or dialog methods.
- Native elements before custom widgets. Justify using the right native element and its API before recreating a control with divs or custom code.
- HTML versus plain text. Distinguish innerHTML from textContent when changing an element’s content, including why untrusted content calls for care.
- Dynamic node insertion. Explain why the section prefers creating and inserting nodes over repeatedly using innerHTML for dynamic UI.
- Attributes and live properties. Explain where attributes and properties live and why their values can differ after a page loads, using a form control as an example.
- Reflected attribute synchronization. Describe what makes an attribute reflected and how changes in either direction stay in sync, including how a boolean attribute represents its state.
- Non-reflected attributes and dataset. Distinguish non-reflected attributes from reflected ones and describe how to access non-reflected attributes and data-* attributes.
- Safe UI node creation. State that createElement and createTextNode are the safest methods presented here for building new HTML UI.
- Moving versus recreating nodes. Explain that moving a DOM node relocates rather than copies it, and why moving existing nodes when reordering a list preserves their state and event listeners.
- Data attributes and dataset. Explain how JavaScript accesses an element’s data attributes through dataset, including string values, name conversion, and what happens when a dataset value changes.
- State-driven styling with classes. Explain why classes or data attributes are preferred for styles that depend on state, especially in a large Vanilla project.
- CSSOM rules and stylesheets. Describe what CSSOM exposes, how constructable stylesheets can be adopted, and when direct rule manipulation is warranted.
- Browser events and default actions. Explain how browser events notify code of interactions or system updates, and distinguish handling an event from canceling its default browser action.
- Event handler attachment choices. Distinguish on* properties from addEventListener, including their handler limits, listener options, and removal requirements.
- DOM event propagation phases. Trace capture, target, and bubble for a click, and explain the default listener phase and the two propagation-stopping methods.
- Container-based event delegation. Explain how a container listener handles child interactions, why it can replace many child listeners, and how target differs from currentTarget.
- Custom event communication. Describe how CustomEvent and dispatchEvent let modules or components communicate, including the optional detail payload and the caution about global events.
- Browser APIs beyond the DOM. Explain that the DOM is one part of a larger set of built-in browser APIs, exposed through objects such as navigator, window, and document, for tasks including clipboard access, media playback, and sensors.
- Secure context requirements. Explain why an app should be tested over HTTPS or localhost when using browser APIs, and what can happen otherwise.
What it builds on
- Using the Right Element (chapter 3) · Choosing an HTML element appropriate to its purpose.
- Custom properties (variables) (chapter 4) · Introduces CSS custom properties as variables.
Section by section
Introduction
Introduces the DOM as the browser’s in-memory document tree and explains why native APIs and careful updates are enough to build interfaces without a library.
- DOM document tree: Explain that the DOM is an in-memory representation of the document used by the rendering engine to paint the page, with elements, text, and comments arranged as related nodes.
Why it matters: Thinking of the page as a tree makes JavaScript UI changes easier to reason about. - Native DOM capabilities: Describe why a library is not required for basic DOM work: the browser platform already supplies selectors, node constructors, insertion and removal helpers, and events.
Why it matters: You can reach for browser-provided DOM tools before adding a dependency. - DOM change performance: Explain why performance matters when changing the DOM: many uncoordinated edits can create additional layout and painting work that affects the user experience.
Why it matters: DOM updates can affect how smoothly the page responds to users.
Key terms: DOM, tree of nodes, parent, children, siblings, selectors, node constructors, insertion and removal helpers, event system, layout
6.1 The DOM tree
The section explains how document elements become DOM objects that JavaScript can access and change, and why DOM changes do not repaint immediately.
- DOM element objects: Explain that each document element is represented by an object with properties and methods, using HTMLElement or an interface that inherits from it.
Why it matters: This connects the elements in HTML to the objects JavaScript uses to change the page. - DOM updates and repaint timing: Distinguish a synchronous DOM update from the later browser repaint, and explain why the browser batches changes until the current JavaScript task finishes and the main thread is free.
Why it matters: It explains why an immediate DOM change need not appear on screen immediately. - Element references and changes: Describe how to obtain an existing element by querying the document or create and insert a new one, then use an element reference to change the UI.
Why it matters: It connects DOM element objects to the basic ways an app updates its interface.
Key terms: DOM, HTMLElement interface, properties, methods, synchronously, main thread, repaint, reference, querying the document, inject it into the DOM
6.2 The API
This section introduces the DOM’s core node types, explains how JavaScript changes reach the screen, and gives practical guidance for handling collections and choosing APIs.
- Core DOM node types: Describe the roles of Document, Element, and Text nodes, and explain how parentNode and childNodes relate nodes in the tree.
Why it matters: These distinctions give you a way to describe what JavaScript is accessing in the DOM tree. - DOM changes and rendering: Explain how the DOM tree originates and how JavaScript mutations become visible.
Why it matters: It connects changes made through the DOM API to what users see. - Live and static collections: Distinguish a live HTMLCollection from the static NodeList returned by querySelectorAll, and describe why a collection might be converted to an array.
Why it matters: Whether a collection changes with the DOM affects how you use its results. - Purposeful DOM API choices: State which simple DOM primitives the section recommends for plain text, structure, and specialized element values.
Why it matters: Choosing an API that matches the task makes the intended DOM change clearer.
Key terms: Document, Element, Text, parentNode, childNodes, parsed HTML, DOM tree, mutations, layout, paint
6.2.1 HTMLElement interface
Introduces the shared HTMLElement interface, specialized element APIs, and preferred ways to manage classes, data attributes, and styles.
- Shared and specialized element APIs: Explain that HTMLElement provides properties shared by most HTML elements, while concrete subclasses provide element-specific properties and methods that avoid string parsing.
Why it matters: The appropriate element API often gives you direct access to what you need. - Class data and style management: Justify using classList and dataset rather than manipulating class and data attribute strings, and explain why CSS classes are generally preferred to inline styles.
Why it matters: These choices make element updates more direct while leaving styling to CSS.
Key terms: HTMLElement, HTMLInputElement, HTMLAnchorElement, classList, dataset, data-* attributes, style, CSS classes
6.2.2 Global DOM objects
This section identifies the main objects through which a page accesses the DOM API and distinguishes the DOM from the broader global environment.
- Window document and node roles: Describe how window, document, and objects representing elements or other nodes relate to a page: window is the browsing context’s global object, document represents the active document and hangs from window, and document nodes have objects that code can reference.
Why it matters: These roles help you identify which object represents the page and which represents an individual node. - Global environment versus DOM: Distinguish the DOM from everything available globally, and explain that globalThis is the ES2020 way to access the current context’s global object, such as window on a standard page navigation.
Why it matters: It prevents you from treating every feature reached through the page’s global object as part of the DOM.
Key terms: window, document, browsing context, nodes, globalThis, DOM, global object
6.2.3 Working with different documents
This section explains how separate DOM documents, same-origin restrictions, off-DOM construction, and cross-document node ownership affect working with nodes.
- Separate documents and access: Explain that iframes, popups, and in-memory documents each have their own document and node tree, and distinguish DOM access from communication across origins.
Why it matters: It helps you tell the difference between accessing another document’s DOM and sending it a message. - Off-DOM content construction: Describe the options the section gives for building content away from the live document before moving nodes into it.
Why it matters: These options let you prepare nodes before placing them in the live document. - Cross-document node ownership: Distinguish transferring a node with adoptNode() from cloning it with importNode() when working across documents.
Why it matters: The distinction determines whether you move the original node or make a destination-owned copy.
Key terms: document, node tree, same-origin policy, postMessage, off-DOM construction, DocumentFragment, template element, DOMParser, detached document, adoptNode()
6.2.4 Querying the document
Explains what DOM queries return, how live collections behave, and how to choose and scope selectors.
- DOM query return types: Distinguish a query that returns one Element or null from one that returns a collection, and compare HTMLCollection with NodeList by contents and whether they update as the DOM changes.
Why it matters: The return type determines what you can do with a query result and whether it changes after the query. - Live collections and snapshots: Explain the risk of changing matching elements while iterating a live collection and when to convert a DOM collection into an array.
Why it matters: Taking a snapshot can make DOM-changing loops predictable while also giving you array methods. - Intentional scoped selectors: Compare classic getters with CSS-selector queries, and explain how intentional selectors and container-scoped searches reduce coupling.
Why it matters: A selector tied to a clear purpose and a small search area is less likely to break or affect an unrelated part of the page.
Key terms: Element, null, HTMLCollection, NodeList, live, static, live collection, Array.from, spread operator, getElementById
6.2.5 Browsing the tree
This section explains how to move through the DOM tree from an element and reminds readers that the tree contains more than HTML elements.
- DOM tree navigation: Explain how an HTMLElement can serve as a starting point for browsing parents, children, and siblings, and why browsing the DOM may encounter nodes other than HTML elements.
Why it matters: It helps you navigate from an element you already have without assuming every node you encounter is an HTML element.
Key terms: DOM tree, HTMLElement, parents, children, siblings, text nodes
6.2.6 Elements available
This section explains that HTML elements have built-in APIs and why code should use those capabilities while checking what each element supports.
- Element-specific native APIs: Explain that HTML tags have corresponding interfaces whose properties, methods, and events provide behavior suited to each element. Give an example such as media playback, form values, details open state, or dialog methods.
Why it matters: An element’s own API may already provide the behavior your code needs. - Native elements before custom widgets: Justify using the right native element and its API before recreating a control with divs or custom code.
Why it matters: Using what the browser already provides can avoid rebuilding important behavior yourself. - Capability checks for mixed nodes: Describe how type checks and feature checks let code handle heterogeneous nodes according to the capabilities each element exposes.
Why it matters: A capability check helps avoid treating every node as though it supports the same API.
Key terms: interface, native element, element’s own API, accessibility, keyboard behavior, semantics, type checks, feature checks, heterogeneous nodes, instanceof
6.2.7 Modifying elements
Explains ways to modify an element and how to choose safer methods for text, dynamic content, and visual states.
- HTML versus plain text: Distinguish innerHTML from textContent when changing an element’s content, including why untrusted content calls for care.
Why it matters: Choosing the right content-setting method helps prevent untrusted data from becoming unwanted HTML. - Dynamic node insertion: Explain why the section prefers creating and inserting nodes over repeatedly using innerHTML for dynamic UI.
Why it matters: This gives you a safer, clearer default for updating a dynamic interface. - Element properties and visual states: Describe the other changes the section says can be made to an element, and how classList helps express visual states.
Why it matters: Content replacement is only one option; classes can express visual changes without relying heavily on inline styles.
Key terms: innerHTML, textContent, XSS, DOMPurify, append, prepend, before, after, replaceWith, property values
6.2.8 Properties vs. attributes
This section distinguishes DOM attributes from JavaScript properties, explains when they stay in sync, and briefly contrasts direct DOM updates with Virtual DOM updates.
- Attributes and live properties: Explain where attributes and properties live and why their values can differ after a page loads, using a form control as an example.
Why it matters: This distinction helps you choose the value that represents the current state rather than assuming the markup and object still agree. - Reflected attribute synchronization: Describe what makes an attribute reflected and how changes in either direction stay in sync, including how a boolean attribute represents its state.
Why it matters: Reflection tells you when direct property access will also update the corresponding markup attribute. - Non-reflected attributes and dataset: Distinguish non-reflected attributes from reflected ones and describe how to access non-reflected attributes and data-* attributes.
Why it matters: Choosing the right access path prevents you from expecting a direct property to track an unrelated attribute. - Virtual DOM update approach: Explain, at the level described here, how a Virtual DOM updates the real DOM and why it is not always required for performance today.
Why it matters: It puts direct DOM work in context without treating a Virtual DOM as a prerequisite for a fast interface.
Key terms: attributes, properties, HTMLElement, reflected attribute, disabled, open, non-reflected attribute, getAttribute, setAttribute, data-*
6.2.9 Creating elements
This subsection recommends safe methods for creating HTML UI and an in-memory buffer for inserting many nodes.
- Safe UI node creation: State that createElement and createTextNode are the safest methods presented here for building new HTML UI.
Why it matters: These are the section’s recommended methods for creating UI nodes. - Buffered insertion of many nodes: Explain that when inserting many nodes, they should first be built in a DocumentFragment in memory to avoid intermediate reflows.
Why it matters: Buffering many nodes avoids intermediate reflows during insertion.
Key terms: createElement, createTextNode, DocumentFragment, in-memory buffer, intermediate reflows
6.2.10 Element arrangement
This section explains how moving existing DOM nodes differs from recreating them and recommends batching multi-node rearrangements for performance.
- Moving versus recreating nodes: Explain that moving a DOM node relocates rather than copies it, and why moving existing nodes when reordering a list preserves their state and event listeners.
Why it matters: Moving existing elements can keep their behavior and state intact during a reorder. - Batching multi-node rearrangements: Describe how to rearrange multiple nodes using a fragment or detached container, and why attaching it once can improve performance.
Why it matters: Batching DOM changes can make rearrangements feel faster.
Key terms: node, state, event listeners, fragment, detached container, layout recalculations, perceived performance
6.2.11 Custom properties with dataset
This section explains how to use data attributes through dataset for small element metadata and where not to use them.
- Data attributes and dataset: Explain how JavaScript accesses an element’s data attributes through dataset, including string values, name conversion, and what happens when a dataset value changes.
Why it matters: It lets you read and change small pieces of element metadata while understanding what appears in the HTML and DevTools. - Appropriate dataset uses: Describe suitable uses for data attributes and explain when to use in-memory structures instead.
Why it matters: Keeping complex state out of dataset makes it a better fit for the small metadata it is meant to hold.
Key terms: data attributes, dataset, kebab-case, camelCase, behavior hooks, IDs, flags, tiny configurations, in-memory structures
6.2.12 Working with styles
This section explains how to choose between classes, inline styles, CSS custom properties, and CSSOM when working with styles from JavaScript.
- State-driven styling with classes: Explain why classes or data attributes are preferred for styles that depend on state, especially in a large Vanilla project.
Why it matters: Keeping visual rules in CSS makes state-driven styling simpler to maintain. - Inline styles and computed styles: Distinguish when an inline style is appropriate from when to use getComputedStyle.
Why it matters: These tools serve different purposes: setting a particular value and diagnosing the final result. - CSS custom properties bridge: Describe how JavaScript and CSS can work together through CSS custom properties.
Why it matters: Custom properties let JavaScript supply values without taking over the CSS rules that use them. - CSSOM rules and stylesheets: Describe what CSSOM exposes, how constructable stylesheets can be adopted, and when direct rule manipulation is warranted.
Why it matters: CSSOM is useful when code must manage rules themselves, but ordinary state styling rarely needs that complexity.
Key terms: classes, data attributes, cascade, media queries, inline style, getComputedStyle, CSS custom properties, variables, :root, var()
6.2.13 Working with events
This section explains how to handle DOM events with listeners, propagation, delegation, and custom events.
- Browser events and default actions: Explain how browser events notify code of interactions or system updates, and distinguish handling an event from canceling its default browser action.
Why it matters: It helps you respond to an interaction without confusing your handler with the browser’s built-in behavior. - Event handler attachment choices: Distinguish on* properties from addEventListener, including their handler limits, listener options, and removal requirements.
Why it matters: Choosing addEventListener gives a real app more control over composing and removing handlers. - DOM event propagation phases: Trace capture, target, and bubble for a click, and explain the default listener phase and the two propagation-stopping methods.
Why it matters: The event path determines which listeners run and when. - Container-based event delegation: Explain how a container listener handles child interactions, why it can replace many child listeners, and how target differs from currentTarget.
Why it matters: Delegation can handle a large collection with one listener while still identifying the child that was used. - Custom event communication: Describe how CustomEvent and dispatchEvent let modules or components communicate, including the optional detail payload and the caution about global events.
Why it matters: Custom events offer a way for parts of an app to communicate without directly depending on one another.
Key terms: event, event listener, default browser action, preventDefault, on* properties, addEventListener, removeEventListener, passive, once, capture phase
6.3 Browser Web APIs
This section places the DOM among the browser’s built-in Web APIs and explains two checks before using them: secure-context requirements and browser compatibility.
- Browser APIs beyond the DOM: Explain that the DOM is one part of a larger set of built-in browser APIs, exposed through objects such as navigator, window, and document, for tasks including clipboard access, media playback, and sensors.
Why it matters: It broadens the set of browser features you can consider using without adding a library. - Secure context requirements: Explain why an app should be tested over HTTPS or localhost when using browser APIs, and what can happen otherwise.
Why it matters: Testing on a secure origin early can reveal access problems before they become surprises. - Browser API compatibility: Distinguish broadly available Baseline APIs from experimental APIs and describe how to check browser support.
Why it matters: Checking compatibility helps you avoid relying on an API that your users’ browsers may not support.
Key terms: DOM, Web APIs, navigator, window, document, secure context, HTTPS, localhost, secure origin, Baseline
6.4 Summary
Where this is used later
- Use cases (chapter 7) · Familiarity with HTMLElement as a DOM interface.
- The Template Content HTML Element (chapter 8) · introduces further work with the template element
- Using DOM APIs (chapter 11) · Rendering routes with DOM APIs requires finding the intended elements to update.
- Creating a Custom Template Engine (chapter 8) · Assumes familiarity with traversing the DOM tree.
- Rendering content (chapter 7) · Introduces modifying DOM elements.
- Basic tips (chapter 14) · Introduces modifying DOM elements.
- Update the component observing properties (chapter 7) · Observing component properties relies on distinguishing live properties from attributes.
- data-* vs standard attributes (chapter 7) · Introduces DOM attributes as distinct from properties.
Concepts explained in this chapter
- CustomEventA script-created DOM event that can carry application-specific data and participate in event propagation.
- addEventListeneraddEventListener is a DOM API method that registers a callback for events of a specified type on an event target.
- event delegationAn event-handling technique that registers a listener on an ancestor and identifies relevant descendant interactions from the event.
- bubble phaseThe event-propagation stage in which an event travels from its target back through ancestor elements.
- event capturingThe event-propagation stage in which an event travels down the DOM tree toward its target.
- event phaseA stage in an event's traversal through the DOM, consisting of capture, target, or bubble processing.
- handlerAn event listener is a callback registration that causes code to run when a specified event occurs.
- Document Object ModelThe browser programming interface for querying and manipulating a document's DOM representation.
- datasetA DOM property that exposes an element’s data-* attributes through a camelCase-keyed object of string values.
- data attributeA custom HTML attribute whose name begins with data- and whose value stores application-specific information on an element.
- HTMLElement APIHTMLElement is the base browser interface implemented by most concrete HTML element objects and their shared properties and methods.
- DOM fragmentA lightweight DOM container that holds a subtree of nodes without being part of the document tree itself.
- textContenttextContent is a DOM node property that gets or sets the plain text content of a node and its descendants without parsing markup.
- CSS variableA CSS custom property is an author-defined property whose value can be inherited and reused in CSS declarations through the var() function.
- constructable stylesheetA constructible stylesheet is a programmatically created CSSStyleSheet that can be adopted and shared by document or shadow roots.
- vanilla webAn approach to building websites and web applications with core web technologies and browser APIs without a framework defining the application architecture.
- attributeA JavaScript property is a named value associated with an object.
- Web APIsA programming interface exposed by a web browser for accessing web-platform or device capabilities.
- apiAn API surface is the set of interfaces and operations that software exposes for external use.
- dispatchEventdispatchEvent is a DOM API method that synchronously dispatches an event to an object and its event listeners.
- HTML template elementThe HTML <template> element holds inert markup that can later be cloned and inserted into a document or shadow DOM.
- BaselineA WebDX initiative that reports when web platform features reach specified levels of availability across major browsers.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
