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

Demonstrated with a Weather Station Analogy

$el: The Current Sensor

Analogy: A single sensor that can report or change its own state. $el refers to the DOM element the directive is on. It's for self-manipulation.

Interactive Demo

Click the sensor below.

Code Example

<!-- HTML -->
<div @click="checkSensor($el)">...</div>

// Alpine.js Component
checkSensor(element) {
  // $el is passed as an argument
  this.log('`$el` sensor activated itself.');
  element.textContent = 'Status: Active!';
  element.classList.remove('bg-gray-400');
  element.classList.add('bg-green-500');
}

$refs: Named Instruments

Analogy: A central panel accessing specific, named instruments. $refs provides access to elements explicitly marked with x-ref within the component.

Interactive Demo

Control Panel

Click to read an instrument.

Anemometer (Wind Speed)
Thermometer (Temperature)
Barometer (Pressure)

Code Example

<!-- HTML -->
<button @click="read('thermometer')">...</button>
<div x-ref="thermometer">...</div>

// Alpine.js Component
readInstrument(name) {
  // Access element via this.$refs
  this.log(`Reading from '${name}' via $refs.`);
  const instrument = this.$refs[name];
  instrument.classList.add('bg-yellow-300', 'font-bold');
}

$root: The Entire Facility

Analogy: An action that affects the entire station facility. $root refers to the root DOM element of the entire Alpine component.

Interactive Demo

The entire white-background component is the "Facility". Click a button to affect it.

Code Example

<!-- HTML (root element) -->
<div x-data="weatherStation">
  <button @click="runSystemCheck">...</button>
</div>

// Alpine.js Component
runSystemCheck() {
  this.log('`$root` initiated system check.');
  // this.$root is the component's root div
  this.$root.classList.add('border-red-500', 'shadow-2xl');
}

Status Log

Awaiting user actions...