Reference
API Reference
Every function and method mx.js exposes. The classic script adds four globals and the ES module exports the same four names: mx, dom, define and components. Signatures below follow the shipped types in mx.d.ts, with one gap. The direct calls mx(tag, ...) and dom(tag, ...) work at runtime but are not typed yet, so in TypeScript use mx.tag() and dom.tag().
At a glance#
mx has four API bindings, two public methods on every element and two more on component elements.
mx()mx(tag, attrs?, ...children)Describe an element for render()mx.tag()mx.tag(attrs?, ...children)The same, through the Proxydom()dom(tag, attrs?, ...children)Create a real element nowdefine()define(name, { $, ... })Register a component tagcomponentsRecord<string, definition>The component registryrender()el.render(...children)Reconcile children into an element$attrs()el.$attrs(attrs)Batch-set attributes and properties$()el.$(props?)Merge props into state and re-render$stateel.$stateState that persists across rendersmx()#
Creates a lightweight element description: a plain array marked with _ = 1. It is not a DOM node. render() reconciles it against the live DOM.
mx(tag: string, attrs?: MxAttrs | MxChild, ...children: MxChild[]): MxDescription
mx.tag(attrs?: MxAttrs | MxChild, ...children: MxChild[]): MxDescriptionParameters
| Name | Type | Description |
|---|---|---|
| tag | string | Element name. camelCase converts to kebab-case: myWidget becomes my-widget. |
| attrs | MxAttrs | MxChild | Optional. Taken as attributes only when it is a plain object (its prototype is Object.prototype) with no nodeType. Anything else, a DOM node or another description included, is the first child. |
| ...children | MxChild[] | Descriptions, DOM nodes, strings, numbers and plain arrays of them (flattened, nested arrays too). null, undefined and false are skipped. |
Returns
MxDescription - the array [tag, attrs | null, children], ready for render().
mx is a Proxy: call it directly, or read a tag helper off it and destructure.
Example
// Direct call
mx('div', { class: 'box' }, 'Hello');
// Proxy destructuring (most common)
let { div, span, button, h1 } = mx;
div({ class: 'box' }, span('Hello'));
// CamelCase auto-converts to kebab-case
mx.myComponent({ prop: 'value' });
// equivalent to: mx('my-component', { prop: 'value' })The kebab conversion is unconditional, so mx.clipPath() emits <clip-path> and mx.linearGradient() emits <linear-gradient>: elements that parse and paint nothing. The same goes for foreignObject, radialGradient, textPath, animateTransform and every fe* filter primitive. Build those with document.createElementNS and pass the node in as a child, because render() places real nodes by identity.
dom()#
Creates and returns an actual DOM element immediately. Same Proxy and destructuring pattern as mx, but it produces live nodes instead of descriptions.
dom(tag: string, attrs?: MxAttrs | MxChild, ...children: MxChild[]): Element
dom.tag(attrs?: MxAttrs | MxChild, ...children: MxChild[]): ElementParameters
| Name | Type | Description |
|---|---|---|
| tag | string | Element name, camelCase converted to kebab-case. |
| attrs | MxAttrs | MxChild | Optional. Same plain-object rule as mx(). On a component it is the props object. |
| ...children | MxChild[] | Rendered into the new element. Ignored when a component gets an attrs object. |
Returns
Element - the new element, already populated. The types give a known tag its own element type (HTMLInputElement for dom.input()) and any other tag an MxElement.
What it does
- Plain element: renders the children first, then applies
attrsthrough$attrs(). - Component with an attrs object: calls
element.$(attrs)and returns the element. Pass{}to initialize one with no props:dom.widget({}). - Component without one:
$is never called, and the children are rendered like on a plain element.
Example
// Direct call - returns a real DOM element
let box = dom('div', { class: 'box' }, 'Hello');
document.body.appendChild(box);
// Proxy destructuring
let { div, input } = dom;
let field = input({ type: 'text', '.value': 'hello' });
document.body.appendChild(field);
// With components - calls $() and returns the element
let btn = dom('a-button', { label: 'Click me' });Use mx() inside render() calls for efficient reconciliation. Use dom() when you need a real element immediately: to store a reference, call methods on it, or hand it to third-party code.
dom.svg() creates an SVG element, but every other SVG tag lands in the HTML namespace: dom.path() serializes as <path d="..."> and never paints. Build SVG subtrees with mx inside a rendered svg (render() namespaces its children), or with document.createElementNS.
define()#
Registers a component tag name. When mx creates an element with that tag, it copies the definition's methods onto the element instance. The special $ method is the render function.
define(name: string, definition?: MxComponentDefinition): voidParameters
| Name | Type | Description |
|---|---|---|
| name | string | Tag name, camelCase converted to kebab-case like at mx() and dom() call sites. |
| definition | MxComponentDefinition | Optional, defaults to {}. Methods and properties mixed into every element of this tag. $ is the optional render function. |
Returns
void - the definition is stored in components under the tag name.
Example
define('my-counter', {
$({ count = 0 }) {
let { div, button, span } = mx;
return div(
button({ onclick: _ => this.$({ count: count + 1 }) }, '+'),
span(count)
);
}
});
// Usage with mx()
document.body.render(
mx.myCounter({ count: 5 })
);
// Usage with dom()
let counter = dom('my-counter', { count: 5 });The $ function
$ is the core of every component. this is the element. It receives the state object (incoming props merged into this.$state) and returns one description or an array of children. Returning nothing renders nothing.
define('greeting', {
$({ name = 'World' }) {
// this = the DOM element
// this.$state = persistent state across renders
// Return children (array or single mx array)
return mx.div(
mx.h2('Hello, ' + name),
mx.p('Welcome to mx.js')
);
}
});The methods are copied when render() or dom() creates the element. A tag already in the HTML, or one made with document.createElement, stays a plain element. Define components before the first render that uses them.
el.$() and $state#
Every element created from a define() with a $ gets $(). $state is created by the first $() call, so it is undefined until then (dom.tag() with no attrs never calls $).
$(props?: Record<string, any>): this
$state: Record<string, any>Parameters
| Name | Type | Description |
|---|---|---|
| props | Record<string, any> | Optional. Merged into this.$state with Object.assign before $ runs. |
Returns
this - the element, after its children have been reconciled.
What $ receives
When called via render(), the argument is the attributes object from mx('tag', attrs), merged into this.$state via Object.assign. When called directly as element.$(newState), the argument is merged the same way. On a component, those attributes are props only: they are not written to the element as HTML attributes, and the description's children are not rendered.
this.$state
A plain object that persists across renders. Every $ call runs Object.assign(this.$state, props) before your function, so $state always reflects the most recently merged props. You rarely reference it directly: destructure from the argument and call this.$({...}) to update.
$({ count = 0 }) {
// count is destructured from $state after the merge.
// Default (= 0) applies on first render when nothing has been set.
return mx.button({
onclick: _ => this.$({ count: count + 1 })
}, count);
}For the rare case of seeding a value that can't come as a prop (stable IDs, component-owned Sets) and needs to be externally readable, this.$state.x ??= defaultValue is available. For internal-only state (intervals, caches, DOM refs) use this._x instead - see $state vs this._property.
this.render()
Available on every element (it lives on Element.prototype). Inside a component, the wrapper calls render() with whatever $ returns.
el.render()#
The core reconciliation method, on Element.prototype. It accepts any mix of mx descriptions, DOM nodes, strings, numbers and plain arrays of them.
render(...children: MxChild[]): thisParameters
| Name | Type | Description |
|---|---|---|
| ...children | MxChild[] | Descriptions, DOM nodes, strings, numbers and plain arrays of them (flattened, nested arrays too). null, undefined and false are skipped, while 0 and '' are rendered as text. |
Returns
this - for chaining.
Behavior
- Walks children left to right, reusing the existing DOM node at each position when its tag name matches, and replacing it when not.
- Text nodes are updated in place when their content changes.
- A plain array (an unspread
.map()result) is flattened into the child list, and so are arrays nested inside it. A description is an array too, but it carries._and stays one element. - Real DOM nodes are placed by identity, not position: a node that is already present is kept (with its focus, selection and scroll) and moved only if needed.
- On a plain element, children are reconciled before attributes, so a
<select>'svaluelands after its<option>s exist. - A component child gets its attributes as props:
render()calls its$and leaves the rest to it. - Inside an
svg, new elements are created in the SVG namespace (except underforeignObject). - Excess old children are removed. New children are appended.
Example
let { div, span } = mx;
let container = document.getElementById('app');
// Initial render
container.render(
div({ class: 'box' }, span('Hello')),
div({ class: 'box' }, span('World'))
);
// Update - mx diffs and patches minimally
container.render(
div({ class: 'box active' }, span('Hello!')),
div({ class: 'box' }, span('World'))
);el.$attrs()#
Sets attributes and properties on an element using the same prefix system as render() - but a plain key is always setAttribute. The checked/selected/value property writes belong to render() alone. dom() applies its attrs through $attrs, so the same holds for dom.select({ value }).
$attrs(attrs: MxAttrs): thisParameters
| Name | Type | Description |
|---|---|---|
| attrs | MxAttrs | Keys as in the attribute prefix table below. Each key is applied once, in order. |
Returns
this - for chaining.
Example
el.$attrs({
class: 'active', // setAttribute('class', 'active')
placeholder: 'Type here', // setAttribute('placeholder', 'Type here')
'.value': 'hello', // el.value = 'hello'
'.checked': true, // el.checked = true
onclick: fn, // el.onclick = fn (functions are assigned as properties)
disabled: null, // el.removeAttribute('disabled')
hidden: false // el.removeAttribute('hidden')
});Differences from render()
$attrs is a thin attribute setter, not a full reconciler. Three asymmetries with render():
- Event handlers can't be cleared via $attrs.
$attrs({ onclick: null })callsremoveAttribute('onclick')- a no-op for handler properties. The previously assigned function stays attached. To remove a handler imperatively, doel.onclick = nulldirectly. - $attrs never writes the value/checked/selected properties. A plain
$attrs({ checked: true })only callssetAttribute. On a fresh<input>that looks right - the attribute still reflects into the property - but once the user has touched the control the attribute no longer drives it, so re-asserting the same value does nothing:input.$attrs({ checked: true })after a click leavesinput.checked === false, and$attrs({ value: 'b' })after typing leaves the property on the typed text while the attribute reads"b".<select>and<textarea>have novalueattribute at all, sodom.select({ value: 'b' })anddom.textarea({ value: 'hi' })leave the browser default (the first option) selected and the textarea empty even when fresh - the same goes for$attrson them. Use the.-prefix for the property path ('.checked': state,'.value': v), or userender(), which dual-tracks both. - $attrs doesn't clear value/checked/selected properties either. Once the control is dirty (the user clicked it, or
.checkedwas written),el.$attrs({ checked: null })removes the attribute but leavesel.checked === true. A pristine checkbox still follows its attribute.render()handles this via the element's attribute cache, but$attrsdoes not.
// the user has just unticked the box
input.$attrs({ checked: true });
input.checked; // still falseinput.$attrs({ '.checked': true });
input.checked; // trueIf you need full cleanup semantics, call render() with fresh descriptions instead of mutating attrs directly.
Attribute prefixes#
MDN explains how HTML attributes and DOM properties relate. The mx rules below determine which one a description writes.
The attribute system recognizes these patterns in both render() and $attrs() (and therefore dom(), which goes through $attrs). The dual-tracking of checked/selected/value noted below is render() only - $attrs and dom() do setAttribute/removeAttribute and nothing else for a plain key - see Differences from render().
| Syntax | Kind | Behavior | Example |
|---|---|---|---|
| name | Standard attribute | setAttribute(name, value). In render() only, checked/selected/value also set the property. | class: 'box' |
| .name | Property | Directly sets el[name] = value. Bypasses attributes entirely. Dropped on a later render(), it is set to null - except .value/.checked/.selected, which keep the user's form state. | '.value': 'text' |
| name: null | Removal | removeAttribute(name). In render() only, checked/selected/value also clear the property to ''. undefined does the same. | disabled: null |
| name: false | Removal | Same as null - removes the attribute. | hidden: false |
| name: true | Boolean attribute | setAttribute(name, 'true') - sets the attribute to the string "true" (consistent across mx, dom and $attrs, and correct for enumerated attrs like aria-*). | disabled: true |
| onname: fn | Event handler | Functions are assigned as properties: el[name] = fn. In render(), cleaned up automatically when the handler changes or is removed. | onclick: fn |
mx tracks event handlers in the element's attribute cache. When a handler function changes between renders, the old one is replaced. When a handler is no longer present in attrs, it is set to null automatically.
Three attributes - checked, selected, and value - are dual-tracked by render(): setting one writes the attribute and the DOM property, and dropping one clears the property to ''. $attrs() does neither - it only calls setAttribute/removeAttribute.
On a pristine <input> the difference is invisible, because the attribute still reflects into the property. It appears the moment the control is dirty or the attribute doesn't reflect at all: after the user types, input.$attrs({ value: 'b' }) leaves the property on the typed text. select.$attrs({ value: 'b' }) does nothing to select.value at all, because <select> has no reflecting value attribute (nor does <textarea>), and that is true on a fresh element too. Use the .property prefix ('.value': v) whenever you mean the property - it works identically in both.
components#
A plain object that serves as the global component registry. define(name, methods) stores the methods in components[name], keyed by the kebab-case tag. You can check whether a component is registered:
if (!components['my-widget']) {
define('my-widget', { $() { ... } });
}components is a window property in the classic build. In ESM it is a named export, not a global. Alongside mx, dom, and define, loading the classic script adds these four names to window. mx also augments Element.prototype with render and $attrs. Component elements additionally get $ and $state.
Types#
The npm package ships mx.d.ts. Every name in the Type columns above is exported from it. The direct-call forms mx(tag, ...) and dom(tag, ...) are not typed yet: MxProxy and DomProxy have no call signature, so TypeScript reports them as not callable. Use mx.tag() and dom.tag().
Importing the package declares no globals. If you load the classic script and write TypeScript or use checkJs, reference the classic types once to get mx, dom, define and components as globals.
/// <reference types="@tltdsh/mx/classic" />import type { MxAttrs, MxChild, MxElement } from '@tltdsh/mx';| Type | Shape | Used by |
|---|---|---|
| MxDescription | An Array marked with _ | mx() return value |
| MxChild | MxDescription | Node | string | number | false | null | undefined | readonly MxChild[] | children of mx(), dom(), render() |
| MxAttrs | HTML and SVG attributes with autocomplete, each also taking null or false to remove it (only null on aria-expanded, aria-selected, aria-checked and aria-pressed), plus any string key | attrs of mx(), dom(), $attrs() |
| MxComponentDefinition | { $?(props), [key: string]: any } | define(), components |
| MxElement | HTMLElement with $state, $() and any other key, for mixed-in methods and this._x fields | component elements |
| MxTagFn / DomTagFn | A tag helper: (attrs?, ...children) | mx.tag(), dom.tag() |
| MxProxy / DomProxy / MxDefine | The types of mx, dom and define | mx, dom, define |