Chapter 12: Chapter 12. Working the DOM
The introduction explains why DOM modification matters for dynamic web applications and why understanding it can improve performance even when using a library.
After this chapter you will be able to
- DOM modification and dynamic pages. Explain that modifying the browser’s DOM is a primary way to make web applications respond dynamically to user actions.
- Performance value of DOM understanding. Justify learning how DOM modification works even when a library handles the operations.
- HTML injection use cases. Explain why inserting HTML supplied as a string is useful for dynamic pages, and describe the tradeoff with constructing elements through a DOM API.
- Required HTML element wrappers. Explain why some HTML fragments need enclosing elements before they are parsed, and distinguish the section’s preferred wrapping approach from inserting into a specially created parent.
- HTML string to nodes. Trace how the section uses a wrapper map, a temporary element, and innerHTML to turn a prepared HTML string into DOM nodes.
- DOM fragment batching. Explain why a DOM fragment is useful when inserting a collection of nodes, especially at multiple locations in a document.
- Attribute and property relationship. Explain the two ways to access an element’s id and describe how changing its attribute or property affects the other, without assuming they are always identical.
- Custom attribute access. Describe why custom attributes need DOM attribute methods and how to handle uncertainty about whether a corresponding property exists.
- Style attribute and property. Distinguish an element’s style attribute value from its style property, and describe the style property as an object rather than a string.
- Contents of the style property. Explain which styles appear in an element’s style property and how assigning a value there affects the element’s display.
- CSS and JavaScript style names. Explain why a hyphenated CSS name such as font-size becomes fontSize when accessed as a JavaScript property.
- Style getter and setter helper. Describe how the section’s style function accepts a CSS-style name and acts as either a getter or a setter.
- Sources of computed styles. Explain that an element’s computed style combines browser built-in styles, style-sheet rules, its style attribute, and script changes, and that retrieval can return values not explicitly declared on the element.
- Computed property retrieval. Describe how to obtain an element’s computed style with getComputedStyle and retrieve a property with getPropertyValue. Explain why a helper accepting camel-cased names must convert them to dashed CSS names first.
- Pixel units and exceptions. Explain why a pixel-based numeric style value needs an explicit unit for reliable cross-browser behavior, and why a style helper must not append px to every numeric value.
- Element dimension properties. Explain why height and width style properties may not reveal an element’s actual size, when offsetHeight and offsetWidth are useful, and what happens to those offsets when display is none.
- Hidden element measurement technique. Describe how to temporarily change a nondisplayed element’s styles to measure it without showing it or leaving a gap, then restore its original styles.
- Layout thrashing and recalculation. Explain how alternating DOM writes and layout reads can force repeated, expensive layout recalculations instead of letting the browser batch updates.
- Batched independent DOM operations. Describe how grouping layout reads before DOM writes minimizes layout thrashing when the elements’ dimensions do not depend on each other.
What it builds on
- Parsing the HTML and building the DOM (chapter 2) · Introduces the DOM as the browser parses HTML.
- Terms and operators (chapter 10) · The helper uses a regular expression to transform the supplied name.
- Do you know? (chapter 5) · The meaning of a closure that retains access to surrounding local variables.
Section by section
Introduction
The introduction explains why DOM modification matters for dynamic web applications and why understanding it can improve performance even when using a library.
- DOM modification and dynamic pages: Explain that modifying the browser’s DOM is a primary way to make web applications respond dynamically to user actions.
Why it matters: It connects JavaScript code to the changing page that users see. - Performance value of DOM understanding: Justify learning how DOM modification works even when a library handles the operations.
Why it matters: A library can hide DOM complexity, but understanding it still helps you make performance-conscious choices.
Key terms: Document Object Model (DOM), modifying the DOM, DOM modification, performance, JavaScript library
12.1 Injecting HTML into the DOM
This section motivates injecting HTML strings into the DOM for dynamic pages and explains the tradeoff with constructing elements through a DOM API.
- HTML injection use cases: Explain why inserting HTML supplied as a string is useful for dynamic pages, and describe the tradeoff with constructing elements through a DOM API.
Why it matters: This explains why the chapter works with HTML strings despite the challenges of inserting them correctly.
Key terms: HTML string, DOM, client-side templates, DOM construction API
12.1 Do you know?
This section poses three questions to check the reader’s understanding of HTML injection, DOM fragments, and measuring hidden elements.
12.1.1 Converting HTML to DOM
This section explains how to turn an HTML string into DOM nodes by correcting problematic markup, adding required wrappers, and parsing it with innerHTML.
- Self-closing HTML normalization: Explain why a childless element such as <table/> may need to be rewritten as <table></table> before parsing the string as HTML.
Why it matters: This preprocessing prevents the input markup from being interpreted differently across browsers. - Required HTML element wrappers: Explain why some HTML fragments need enclosing elements before they are parsed, and distinguish the section’s preferred wrapping approach from inserting into a specially created parent.
Why it matters: The wrapper lets the browser create nodes that require a particular HTML context. - HTML string to nodes: Trace how the section uses a wrapper map, a temporary element, and innerHTML to turn a prepared HTML string into DOM nodes.
Why it matters: It connects the markup corrections to the DOM nodes that the application can subsequently insert.
Key terms: self-closing elements, preparse, HTML string, HTML wrapping, container elements, innerHTML, dummy DOM element, wrapper map, DOM nodes
12.1.2 Inserting elements into the document
This subsection shows how to collect converted DOM nodes in a fragment so they can be inserted and cloned efficiently, including at multiple document locations.
- DOM fragment batching: Explain why a DOM fragment is useful when inserting a collection of nodes, especially at multiple locations in a document.
Why it matters: Grouping nodes in a fragment makes repeated insertion less work than handling each node separately. - Fragment-enabled getNodes flow: Describe how the revised getNodes function uses a supplied fragment to prepare converted HTML nodes for insertion.
Why it matters: This change connects HTML-to-DOM conversion with the fragment used for insertion.
Key terms: DOM fragments, DOM nodes, clone, getNodes, fragment parameter, HTML string, DOM elements
12.2 Using DOM attributes and properties
This section explains how DOM attributes relate to element properties and how to access attributes that lack corresponding properties.
- Attribute and property relationship: Explain the two ways to access an element’s id and describe how changing its attribute or property affects the other, without assuming they are always identical.
Why it matters: It helps you interpret what happens when code reads or changes an element through either interface. - Custom attribute access: Describe why custom attributes need DOM attribute methods and how to handle uncertainty about whether a corresponding property exists.
Why it matters: It prevents code from assuming that every HTML attribute is available as an element property.
Key terms: getAttribute, setAttribute, element properties, id attribute, id property, custom attributes, data-
12.3 Styling attribute headaches
Introduces the distinction between a style attribute and an element’s style property, and defines computed style.
- Style attribute and property: Distinguish an element’s style attribute value from its style property, and describe the style property as an object rather than a string.
Why it matters: This distinction helps you describe which representation of an element’s styles you are working with. - Computed style meaning: Explain what computed style means in this section.
Why it matters: Computed style refers to the resulting style, not merely the values specified in the element’s markup.
Key terms: style attribute, style element property, style values, computed style, inherited, applied style information
12.3.1 Where are my styles?
This section explains why an element’s style property contains inline and script-assigned styles but not styles applied from style sheets.
- Contents of the style property: Explain which styles appear in an element’s style property and how assigning a value there affects the element’s display.
Why it matters: A style can visibly affect an element without appearing in its style property. - Priority of style property values: State how values in an element’s style property compare with styles inherited from a style sheet.
Why it matters: It explains why setting a value on the element can override a style inherited from a style sheet.
Key terms: style property, style attribute, style object, style sheets, borderWidth, style sheet, !important
12.3.2 Style property naming
This section explains how CSS style names are accessed in JavaScript, demonstrates a helper for getting and setting styles, and notes a limit of an element’s style property.
- CSS and JavaScript style names: Explain why a hyphenated CSS name such as font-size becomes fontSize when accessed as a JavaScript property.
Why it matters: The naming difference explains why a CSS name cannot simply be copied into JavaScript dot notation. - Style getter and setter helper: Describe how the section’s style function accepts a CSS-style name and acts as either a getter or a setter.
Why it matters: The helper lets callers use familiar CSS names for both reading and writing styles. - Element style property limit: Distinguish the information available through an element’s style property from the full style applied to that element.
Why it matters: Reading an element’s style property alone may not tell you all the styling applied to it.
Key terms: CSS attributes, dot operator, camel case, style function, regular expression, name parameter, getter, setter, style property, style sheets
12.3.3 Fetching computed styles
This section explains what contributes to an element’s computed style and how to retrieve individual computed CSS property values.
- Sources of computed styles: Explain that an element’s computed style combines browser built-in styles, style-sheet rules, its style attribute, and script changes, and that retrieval can return values not explicitly declared on the element.
Why it matters: A computed value may come from beyond the element’s inline style, so checking only that style can miss the value in use. - Computed property retrieval: Describe how to obtain an element’s computed style with getComputedStyle and retrieve a property with getPropertyValue. Explain why a helper accepting camel-cased names must convert them to dashed CSS names first.
Why it matters: Using the right query method and property-name format lets you retrieve the computed value you intended. - Shorthand property retrieval: Explain why a CSS shorthand such as border must be queried through its individual computed properties in this example.
Why it matters: A shorthand that is convenient for writing CSS may not be the property to request when reading back a computed value.
Key terms: computed style, style sheets, style attribute, getComputedStyle, getPropertyValue, camel-cased, dashed, amalgam properties, border, border-top-color
12.3.4 Converting pixel values
Explains how to set pixel-based style values reliably, avoid adding pixel units to unitless properties, and read numeric pixel values.
- Pixel units and exceptions: Explain why a pixel-based numeric style value needs an explicit unit for reliable cross-browser behavior, and why a style helper must not append px to every numeric value.
Why it matters: Distinguishing pixel dimensions from unitless values helps avoid unreliable or incorrect style assignments. - Reading pixel values: State how to obtain the intended numeric value when reading a pixel value from a style attribute.
Why it matters: Parsing a pixel-valued style attribute gives you the number needed for subsequent calculations.
Key terms: style values, pixels, px, nonpixel values, parseFloat, style attribute, pixel value
12.3.5 Measuring heights and widths
This section explains how to measure element dimensions, including elements hidden with display: none, without visibly disturbing the page.
- Element dimension properties: Explain why height and width style properties may not reveal an element’s actual size, when offsetHeight and offsetWidth are useful, and what happens to those offsets when display is none.
Why it matters: Choosing the right properties prevents misleading measurements, especially for hidden elements. - Hidden element measurement technique: Describe how to temporarily change a nondisplayed element’s styles to measure it without showing it or leaving a gap, then restore its original styles.
Why it matters: The technique obtains a hidden element’s dimensions without visibly changing the page. - Measurement helper scope: Explain why the example encloses its replacement-style hash and getDimensions function in an immediate function.
Why it matters: This keeps the helper’s shared style information available without adding it to the global namespace.
Key terms: height, width, auto, offsetHeight, offsetWidth, padding, display, block, visibility, hidden
12.4 Minimizing layout thrashing
This section explains why alternating DOM writes with layout reads hurts performance and how batching updates reduces unnecessary layout recalculations.
- Layout thrashing and recalculation: Explain how alternating DOM writes and layout reads can force repeated, expensive layout recalculations instead of letting the browser batch updates.
Why it matters: It explains why otherwise ordinary DOM operations can become expensive when arranged in the wrong order. - Batched independent DOM operations: Describe how grouping layout reads before DOM writes minimizes layout thrashing when the elements’ dimensions do not depend on each other.
Why it matters: Grouping independent operations avoids making the browser recalculate layout between each change. - Virtual DOM update batching: Describe how React’s virtual DOM lets it batch changes to the actual DOM.
Why it matters: It gives an example of a library using batched DOM updates for better performance.
Key terms: layout thrashing, layout, clientWidth, batch, DOM reads, DOM writes, React, virtual DOM, actual DOM
12.5 Summary
12.6 Exercises
Where this is used later
- Browser bug fixes (chapter 14) · Assumes familiarity with accessing properties on DOM elements.
- External code and markup (chapter 14) · Accessing DOM attributes and properties.
- Untestable browser issues (chapter 14) · CSS styling and style properties
Concepts explained in this chapter
- style propertyA DOM element property that exposes its inline style declarations as a mutable CSSStyleDeclaration object.
- offsetHeightA DOM element property reporting its layout height in pixels, including padding and borders.
- HTML stringA text representation of HTML markup that can be parsed into a document structure.
- offsetWidthA DOM element property reporting its layout width in pixels, including padding and borders.
- getComputedStyleA browser method that returns the computed CSS values for an element after cascading and inheritance are applied.
- innerHTMLA DOM element property that gets or sets HTML markup as the serialized contents of an element.
- layout thrashingA performance problem in browser rendering that happens when repeated DOM reads and writes force frequent synchronous layout recalculations.
- dropdownAn HTML element that provides a control for selecting among options.
- DOM fragmentA lightweight, detached portion of a DOM tree that can be manipulated separately before being inserted into a document.
- html wrappingThe technique of surrounding HTML markup with required container markup before parsing or insertion.
- computed styleThe set of CSS property values resolved for an element after the browser accounts for applicable browser defaults, style sheets, inline declarations, inheritance, and script changes.
- getPropertyValueA CSSStyleDeclaration method that retrieves the computed value of a specified CSS property.
- camel caseA naming convention in which words are joined without spaces and each word after the first begins with a capital letter.
- attributeA named association on an object that holds a value or provides accessor behavior.
- closureA function together with the lexical environment in which it was created, allowing it to access variables from that environment after the outer function has finished executing.
- immediately invoked function expressionA function expression that is defined and invoked immediately in the same syntactic construct.
- MapA collection type that stores key-value associations and supports efficient lookup by key.
- regular expressionA pattern for matching character sequences in text.
- inheritanceA reuse relationship in which one object or type can access properties or behavior defined by another through a hierarchical relationship.
- getterA pair of property accessors that execute custom code when a property is read or assigned.
- setterA property accessor function called when a value is assigned to the property.
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.
