Documents v0.9.0 · previews run the real runtime · experimental features are marked exp

attr()

expressionsince 0.5experimentalrequires runtime

In state() and in mutations: reads an HTML attribute into a state. Everywhere else attr() is the browser’s native function.

On this page · 8 sections+

Syntax

attr(<attribute-name>, <fallback>?)

registry syntax: attr(name [, "fallback"])

Parameters

nameHTML attribute namerequired
Read from the state owner in state(), and from the element the rule matched in a mutation.
fallback<string>, or since 0.9 a typed valueoptional
Used when the attribute is missing. Default "". With a non-string fallback, state(attr(aria-expanded, false)), the attribute is parsed as that type, and an invalid value gives the fallback.

Return value

A string, escaped into one CSS string, or a value of the fallback’s type. An empty attribute gives "".

Example

greeting.cssreactive
.greeting {  --message: state(attr(data-message));  --open: state(attr(aria-expanded, false));}.choice:on(click) {  --message: set(attr(data-message));}
state()Function · hover any red tokenMakes each matching element the owner of an independent state with an initial value.Reference →

Behavior

  • state(attr(name)) reads the owner’s attribute once, when the state is created. Changing the attribute later does not reset the state. For an attribute that should follow the state, use bind(<attribute>).
  • In an :on() mutation, attr(name) reads the attribute of the element the rule matched, once, at the event.
  • Values are never parsed as CSS or as actions: quotes, backslashes and control characters are escaped.

Supported contexts

  • The initial value of --x: state(…), the expression of an :on() mutation. Elsewhere, such as content: attr(data-label), the browser’s attr() is untouched.

Limitations

  • Experimental since 0.5.0.
  • No ancestor lookup and no native typed attr(name type(…)).
  • Trusted stylesheets only, like every event rule and binding. Password, one-time-code and payment fields are never read.

native equivalent · attr() (CSS Values 5) everywhere else: content: attr(data-label) and typed attr(name type(...)) are left to the browser

Experimental · syntax may change between minor versions