Skip to content

reflectAttribute

Defines a property on element that is backed by an HTML attribute — what a custom element needs for <my-card heading="…" count="3" selected>, in one line. Reading parses the attribute by type; writing stores it (a boolean toggles the attribute, null or undefined removes it). The attribute stays the single source of truth, so setAttribute and the property never disagree.

It defines an own property on the instance, so call it once per element (in a constructor or connectedCallback). Calling it again for the same property replaces the previous definition.

Available since v3.1.8

import { reflectAttribute } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { reflectAttribute } from 'helpers4/browser';
reflectAttribute(element: Element, property: string, options: ReflectAttributeOptions): function
ParameterTypeDescription
elementElementThe element that gets the property
propertystringThe property name, e.g. `‘heading’`
optionsReflectAttributeOptionsType, attribute name and default — see ReflectAttributeOptions

function — A function that removes the property again

Writing the property sets the attribute, and setAttribute is seen by the property.

reflectAttribute(card, 'count', { type: 'number' });
card.count = 3;
card.getAttribute('count') // => '3'

A boolean property is the presence of the attribute

Section titled “A boolean property is the presence of the attribute”

Like hidden or disabled: true adds the attribute, false removes it.

reflectAttribute(card, 'selected', { type: 'boolean' });
card.selected = true;
card.hasAttribute('selected') // => true

Options for reflectAttribute.

interface ReflectAttributeOptions {
  attribute?: string;
  defaultValue?: string | number;
  type?: "string" | "number" | "boolean";
}

View source on GitHub