liveBook · Manning

Text node

As explained in Build a Frontend Web Framework (From Scratch)

A browser Document Object Model node that contains textual character data without attributes or child nodes.

A text node stores textual character data without a tag name, attributes, or child nodes. In a virtual DOM, it is represented by a type and a value. section 3.6 section 3.2

Handle a text node through three small responsibilities:

  • Identify it with DOM_TYPES.TEXT, whose value is 'text', so rendering code can distinguish it from element and fragment nodes. section 3.4
  • Create it with a virtual node such as { type: DOM_TYPES.TEXT, value: str }. section 3.6
  • Mount it with document.createTextNode(value), save the real DOM node in vdom.el, and append it to the parent. section 4.1.2
  • Patch only changed text by comparing old and new values and assigning the new value to the DOM node's nodeValue property. section 8.2.4

Create and mount text

const vdom = hString('I need more coffee') mountDOM(vdom, document.body) The virtual node becomes a browser Text node, while vdom.el keeps the reference needed for later updates. section 3.6 section 4.1.2

Listing 8.9 Patching a text node (patch-dom.js)
function patchText(oldVdom, newVdom) {
  const el = oldVdom.el
  const { value: oldText } = oldVdom
  const { value: newText } = newVdom

  if (oldText !== newText) {
    el.nodeValue = newText
  }
}

Inspect the minimal patchText implementation: retain the existing DOM reference, compare values, and update nodeValue only when the text changes. section 8.2.4

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains representation, browser creation, DOM references, and conditional patching, but stops short of broader reconciliation behavior.
Examples
Demonstrates hString(), a coffee message, document.createTextNode(), and patching changed text with nodeValue.
What it assumes
Assumes basic JavaScript objects and DOM concepts while defining node types and text-node handling incrementally.
What you can do after
Build and update virtual-DOM text nodes with hString(), document.createTextNode(), stored DOM references, and nodeValue.
How it connects
Connects text nodes to the virtual DOM, element nodes, fragment nodes, mounting, and the reconciliation algorithm.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.