liveBook · Manning

Attribute

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

A named property of an HTML or DOM element that carries a value describing or configuring that element.

When code changes an element, DOM properties often update the corresponding attributes in the rendered HTML. For example, setting a paragraph’s `id` property changes its rendered `id` attribute. section 4.1.6

The correspondence is not universal: changing an input’s `value` property changes what appears in the field, but does not update the rendered `value` attribute. Read the current input value from its property. section 4.1.6

A DOM attribute setter can divide the work into three paths:

  • Handle `class` separately, accepting either a class string or an array of class names. section 4.1.6
  • Handle `style` separately by setting each supplied style property. section 4.1.6
  • Route other names through a helper; the example uses DOM properties for ordinary names and `setAttribute()` for `data-` names. Remove attributes when their values are null. section 4.1.6
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 setter separates `class` and `style` from other properties, then delegates each path to a helper. section 4.1.6

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

How deep it goes
Distinguishes reflected properties from input values and sketches separate class, style, and general-attribute helpers.
Examples
Uses a paragraph `id`, an input `value`, class strings or arrays, and individual style properties as examples.
What you can do after
Build attribute-setting helpers that handle class and style separately and remove attributes when values are null.
How it connects
Connects attributes with DOM elements, virtual DOM properties, CSS classes, and inline styles.

Also explained in

Compare how 26 books explain attribute →

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.