liveBook · Manning

setAttributes

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

A book-specific function that applies virtual-node attribute values to a DOM element, with special handling for class and style.

setAttributes applies virtual-node attributes to a DOM element while separating class and style from ordinary attributes. This keeps browser-specific behavior inside small helper functions. section 4.1.6 section 4.1.4

The function performs four focused steps:

  • Extract class, style, and the remaining attributes from the attribute object. section 4.1.6
  • Pass class values to setClass, which supports either a class string or an array of class names. section 4.1.6
  • Iterate through style entries and pass each property and value to setStyle. section 4.1.6
  • Pass ordinary attributes to setAttribute, which removes null values, uses setAttribute for data-* names, and assigns other properties directly. section 4.1.6

Mounting an element

When an element node is mounted, event listeners are separated from props first. setAttributes then applies the remaining attributes, while children are mounted recursively. section 4.1.4

Listing 4.3 Setting the attributes of an element node (attributes.js)
export function setAttributes(el, attrs) {
  const { class: className, style, ...otherAttrs } = attrs    #1

  if (className) {
    setClass(el, className)     #2
  }

  if (style) {
    Object.entries(style).forEach(([prop, value]) => {
      setStyle(el, prop, value)                       #3
    })
  }

  for (const [name, value] of Object.entries(otherAttrs)) {
    setAttribute(el, name, value)         #4
  }
}

// TODO: implement setClass

// TODO: implement setStyle

// TODO: implement setAttribute

The implementation makes the routing explicit: destructure class and style, invoke their helpers, then process every remaining attribute. section 4.1.6

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

How deep it goes
Implements attribute routing and helper calls, while deferring detailed class, style, and ordinary-attribute behavior to separate functions.
Examples
Uses input value behavior, class strings or arrays, style objects, data-* attributes, and null-based attribute removal.
What it assumes
Assumes virtual-node props and DOM elements, while teaching their attribute-handling split from the implementation upward.
What you can do after
Build it from scratch by routing virtual-node properties to class, style, and ordinary-attribute helpers.
How it connects
Connects virtual DOM, DOM elements, class attributes, style attributes, ordinary attributes, and event listeners.

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.