Alpine.js: A Concert Hall Analogy

Understanding `$el`, `$refs`, and `$root`

The Orchestra Stage

$el: The Current Musician

A musician can act on themselves. `$el` refers to the DOM element the Alpine directive is on. The action is self-contained.

musician

Ready to play...

Code Example:

<button @click="takeSpotlight($el)">...</button>
                        
// In Alpine.data component:
takeSpotlight(el) {
  // 'el' is the button element itself
  const musician = el.closest('[x-ref=musicianEl]');
  // ... manipulate musician element ...
}

$refs: The Named Instruments

The conductor can call out a specific, named instrument. `$refs` lets you access a named element from anywhere within the component.

Piano 🎹
Violin 🎻
Drums 🥁

Conductor's Commands:

Code Example:

<div x-ref="piano">...</div>
<button @click="spotlightInstrument('piano')">
                        
// In Alpine.data component:
spotlightInstrument(name) {
  const instrument = this.$refs[name];
  // ... manipulate instrument element ...
}

$root: The Entire Orchestra

The conductor can give a command to everyone. `$root` refers to the top-level element of the entire component (`x-data`).

Stage Controls

(Affects this entire white card)

Code Example:

<div x-data="concertHall">
  <button @click="startIntermission()">...</button>
</div>

// In Alpine.data component:
startIntermission() {
  const orchestra = this.$root;
  // ... manipulate orchestra element ...
}