---
title: "hx-live"
description: "Add lightweight reactivity backed by the DOM"
category: "UX"
icon: "icon-[mdi--lightning-bolt]"
keywords: ["live", "reactive", "bind", "q", "selector"]
---
Expressions live in HTML attributes. They read from the page, write to it, and re-run as it changes.
```html
```
The paragraph updates as you type.
## Installing
```html
```
## Attributes
### `:`
Prefix any HTML attribute with `:` and put an expression in it. The result is written to the attribute.
```html
```
The same shape works for any attribute:
```html
profile
```
> ⚠️ **Alpine.js conflict:** The `:` short form uses the same syntax as Alpine.js (`x-bind:`). If Alpine is detected on the page at initialization time, hx-live automatically disables the `:` short form and logs a console warning. You can override this behavior by explicitly setting [`config.live.bindPrefix`](#configlivebindprefix).
How each attribute is written (booleans, ARIA, property-backed, generic) is described in [Attribute writing rules](#attribute-writing-rules).
### `hx-live:`
The full form. Behaves identically to `:`.
```html
```
Use it if your build pipeline strips `:`-prefixed attributes.
### `:.`
Bind a single class to an expression. Truthy adds it, falsy removes it.
```html
Negative balance
```
### `:class`
String form: set the listed classes.
```html
```
Object form: each key is added or removed by the truthiness of its value.
```html
```
A key may list several classes that share one condition. Quote the key when it contains spaces.
```html
Notice
```
`:class` only manages classes it writes. Other classes set in HTML are untouched. If a class appears both statically and in the binding, the binding wins.
### `:text`
Bind the element's [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) to an expression.
```html
```
Numbers and other non-strings are stringified.
### `:html`
Bind the element's [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) to an expression.
```html
```
Make sure to sanitize anything untrusted.
### `:style`
String form: a CSS declaration string.
```html
```
Object form: each key sets a CSS property. Camel-case keys convert to kebab-case.
```html
```
`:style` only manages properties it writes. Other inline style properties are untouched. If a property appears both statically and in the binding, the binding wins.
### `hx-live`
An escape hatch. Use it when no single `:` fits, or for multi-step logic and side effects.
```html
```
## Helpers
The helpers work inside `hx-live` expressions, inside [`hx-on`](/reference/attributes/hx-on) event handlers, and from regular JavaScript via `htmx.live.*`.
```js
htmx.live.q('.row').attr('hidden', true);
```
Inside expressions, `this` is the element, the full htmx API is available unprefixed, and `await` works at the top level (expressions are `async` functions).
```html
```
### `q()`
`q()` returns a proxy over a set of elements. Read from the first match, write to all.
```js
q('.row') // every .row in the document
q('#bar') // single element by id
q(element) // wrap an existing element
q(nodeList) // wrap a collection
q('.row').count // number of matches
q('.row').arr() // Array
for (let e of q('.row')) {...} // iterate
q('input').value // value of the first match
q('input').value = '' // assign to every match
q('.row').classList.add('done') // method calls chain through
q('.row').dataset.state = 'on'
q('button').click()
```
**Selector grammar**
```js
q('first .foo') // first match in document order
q('last .foo') // last match
q('next .foo') // first match after this element
q('previous .foo') // closest match before this element
q('closest .foo') // nearest ancestor matching .foo
q('.foo in #scope') // restrict to a specific root
q('.foo in this') // restrict to the current element
```
`next`, `previous`, and `closest` resolve against `this` (the element that owns the expression). They only work inside `hx-live` / `hx-on` scopes.
**Chaining**
`.q(...)` on a proxy re-runs the grammar with each element as the anchor:
```js
q('.error').q('closest .field') // surrounding .field of each .error
q('section').q('first .item') // first .item per section
q('.row').q('next .row') // each row's successor
```
For plain descendant queries, CSS is shorter: `q('.card .title')` and `q('.card').q('.title')` are equivalent. Use chaining when you need a directional per matched element.
**Built-in methods**
The helpers below also work as methods on the proxy, applying across all matched elements:
```js
q('input').attr('disabled', true) // set attribute on all
q('.row').toggle('.selected') // toggle class on each
q('.tab.active').take('.active', '.tab') // move a class from peers to self
q('.tab').trigger('select', { id: 1 }) // CustomEvent on each
q('.list').insert('end', '
new
') // before / after / start / end
```
### `attr(name, value?)`
Get or set an attribute, class, or property on this element. Pass one argument to read, two to write.
```js
attr('hidden') // is hidden present?
attr('hidden', true) // add (false/null/undefined removes)
attr('.active') // has class .active?
attr('.active', q('#src').checked) // add/remove class
attr('class', 'foo bar') // multi-class string
attr('class', { active: matches('.tab') }) // multi-class object
attr('aria-expanded', matches('.open')) // any aria-*: writes "true"/"false"
attr('value', 'hello') // value/checked/selected: syncs property + attribute
attr('data-x', null) // remove
```
### `toggle(name, values?)`
Toggle (no `values`) or cycle (with `values`) a class or attribute on this element.
```js
toggle('.active') // toggle class
toggle('aria-expanded') // flip "true" ↔ "false"
toggle('hidden') // toggle attribute presence
toggle('data-view', 'grid|list|table') // cycle attribute through values
toggle('.size', 'sm|md|lg') // cycle classes (only one at a time)
toggle('data-open', 'on|') // cycle: 'on' ↔ absent
```
`values` accepts a `|`-separated string or an array.
### `take(name, scope?)`
Move a class or attribute from siblings to this element. Pass a `scope` selector to widen or restrict the source set.
```js
take('.selected', '.tab') // become the selected tab among .tab
take('aria-current', 'nav a') // become the current nav item
take('.active') // implicit scope: parent element's subtree
```
### `data`
Read or write `data-*` attributes on the closest ancestor that has them. Lets components share state up the tree.
```html
```
`data.foo` reads from the closest `[data-foo]` ancestor. Writing assigns to that ancestor too.
Values are automatically JSON-serialized on write and parsed on read. Booleans, numbers, arrays, and objects round-trip transparently:
```html
```
Plain strings that aren't valid JSON are returned as-is.
The `data` proxy is enumerable. Object spread, rest destructuring, and `Object.keys()`/`Object.entries()` use the same cascading lookup rules:
```html
```
Here, `hx-vals` receives `{ x: 1, y: 3 }`.
`data` is also available on `q()` proxies via `q(selector).data`. It cascades from the first matched element:
```js
q('#cart-panel').data.items // read: JSON-parsed value from closest [data-items] ancestor
q('#cart-panel').data.items = [{id: 1}] // write: JSON-stringified to that ancestor
```
For direct, this-only access, use `this.dataset` instead (note: `this.dataset` is always strings). For per-element writes across a set, use `q('.row').dataset.state = 'on'`.
Because `:` works on `data-*`, you can also store derived values in the DOM:
```html
```
### `style`
Shorthand for `this.style`.
```html
```
### `classList`
Shorthand for `this.classList`.
```html
```
### `matches(selector)`
Shorthand for `this.matches(selector)`.
```html
```
### `trigger(type, detail?, bubbles?)`
Dispatch a `CustomEvent` from this element.
```html
Item
```
### `insert(position, html)`
Insert an HTML string. Wraps [`insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) with friendlier position names: `before` and `after` for siblings, `start` and `end` for children.
```js
insert('start', '
first
') // first child
insert('end', '
last
') // last child
insert('before', '') // sibling before
insert('after', '') // sibling after
```
```html
Click to add a row
```
Sanitize anything untrusted.
### `debounce(ms)`
Wait `ms` milliseconds. If called again on the same element before resolving, the previous call is cancelled.
```html
```
Each element has its own channel.
### `forEvent(...args)`
Resolve on the next matching event. Mix event names, milliseconds, intervals, and target elements. First to fire wins.
```js
await forEvent('click') // next click on this element
await forEvent('click', 1000) // click OR 1s timeout
await forEvent('a', 'b', '5s') // any number of events / intervals
```
Typical use: wait for a CSS transition to finish, with a safety timeout.
```html
```
### `nextFrame()`
Resolve on the next animation frame.
```html
```
## ARIA as state
ARIA attributes serve two purposes: they describe the component to assistive tech, and they hold UI state.
Bind them with `:aria-*` and drive CSS off the same attribute. You avoid `.is-open`, `.active`, and `.loading` classes.
| Attribute | Meaning | Typical UI use |
|-----------------|---------------------|---------------------------------------|
| `aria-expanded` | "is open" | Disclosure, menu, accordion |
| `aria-selected` | "is the active one" | Tabs, listbox option |
| `aria-pressed` | "toggle is on" | Toggle button (bold, mute) |
| `aria-checked` | "checkbox state" | Custom checkboxes, radios |
| `aria-busy` | "is loading" | Form during submit, list during fetch |
| `aria-disabled` | "can't interact" | Greyed-out non-button control |
| `aria-current` | "the current one" | Nav item, breadcrumb, step |
| `aria-hidden` | "hidden from a11y" | Decorative content |
**Disclosure.**
For a single inline section, native [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) is the right tool. Use `aria-expanded` when the trigger and target are separated in the DOM.
```html
```
**Toggle button.**
```html
```
```css
[aria-pressed="true"] { background: lightblue }
```
**Tabs.**
```html
```
`take('aria-selected', '[role=tab]')` writes `"false"` on every `[role=tab]`, then `"true"` on this one.
**Loading state.**
```html
```
```css
[aria-busy="true"] { opacity: 0.5; pointer-events: none }
```
**Non-boolean ARIA.** Strings pass through, so `aria-current="page"`, `aria-pressed="mixed"`, and numeric ARIA (`aria-valuenow="50"`) work in the simple form:
```html
Home
```
## How it works
### Re-run triggers
A single document-wide `MutationObserver` and `input` / `change` listeners trigger a recompute of every live expression. Any of these schedule one:
- DOM additions, removals, attribute changes, text changes
- `input` or `change` events from any control
- completion of an htmx swap (recomputes pause mid-swap, run once at the end)
All expressions run in a single microtask, so multiple synchronous mutations coalesce into one recompute.
### Self-mutation is safe
When an expression writes to the DOM, the observer drains its own pending records inside the same microtask. Writes made by `hx-live` cannot trigger a feedback loop.
### Runaway cap
If recomputes exceed 50/sec, the extension logs a warning. Bindings continue running. Tune your expression or add `debounce`.
### Coordinating with htmx swaps
Recomputes are deferred between [`htmx:before:swap`](/reference/events/htmx-before-swap) and [`htmx:swap:finally`](/reference/events/htmx-swap-finally). One consolidated recompute runs when the swap finishes, regardless of how much markup changed.
### Cleanup
When an `hx-live` element is removed, its expression drops out on the next scheduled run. When all expressions are gone, the observer and listeners detach.
[`hx-ignore`](/reference/attributes/hx-ignore) descendants are not registered.
### Boolean, ARIA, and other attribute kinds
[`:`](#attr) writes the value differently depending on the attribute, following HTML conventions.
**Boolean attributes** (`disabled`, `hidden`, `required`, `open`, `readonly`, `inert`, ...). Truthy adds the attribute; falsy removes it.
```html