Alpine.js: $el, $refs, & $root

Understanding magic properties using a Train Station analogy.

[Action Log]

No actions yet. Interact with the demos below.

$el

Analogy: The Current Platform

$el refers to the current DOM element. A platform can announce its own status without needing directions. It acts on itself.

Interactive Demo

Platform 3

Status: Awaiting Train

Code Snippet

<button @click="announceDeparture($el)">...</button>

$refs

Analogy: Named Facilities

$refs lets you access other DOM elements by a name you give them (with x-ref). The control panel can target and operate specific, named facilities.

Interactive Demo

Use the central control panel to manage facilities:

Ticket Booth:
Information Desk:

Code Snippet

// JS: this.$refs.ticketBooth.classList...
// HTML: <div x-ref="ticketBooth">

$root

Analogy: The Entire Station

$root refers to the top-level DOM element of the component. A station-wide alert affects the entire component, no matter where the alert is triggered from.

Interactive Demo

Trigger an event that affects the entire station component (the gray container with the title).

Station is in alert mode!

Code Snippet

// JS, from anywhere in the component:
this.$root.classList.add('station-alert');

Summary: Who are you talking to?

$el

"I'm talking to myself."

(The current element)

$refs

"I'm talking to that specific thing by name."

(A named element elsewhere in the component)

$root

"I'm talking to everyone in the whole station."

(The component's top-level element)