Alpine.js Magic

Understanding $el, $refs, and $root in a Sports Stadium

Game Log

$el: The Current Player

Analogy: A player knows about themself. Clicking a player makes that specific player react.

<button @click="highlightPlayer($el)">
    Player
</button>

$refs: Named Positions

Analogy: A coach calls out to a specifically named position from the sideline.

Coach's Box

Quarterback (x-ref)
Goalie (x-ref)
// JS in component:
this.$refs.quarterback.classList.add(...)

$root: The Entire Field

Analogy: An announcer's call affects the entire stadium field (the component's root element).

Announcer's Booth

The entire green container you see is the $root element. Clicking the button above changes its style.

// JS in component:
this.$root.classList.toggle(...)

Summary: Who is an I?

Concept Analogy Refers To... Scope
$el The Player The DOM element the Alpine directive is on. Element
$refs Named Positions A specifically named DOM element (via x-ref) within the component. Component
$root The Entire Field The top-level DOM element of the component (where x-data is). Component Root