Demonstrated with a Weather Station Analogy
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.
Click the sensor below.
<!-- 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');
}
Analogy: A central panel accessing specific, named instruments.
$refs provides access to elements explicitly marked with x-ref within the component.
Click to read an instrument.
<!-- 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');
}
Analogy: An action that affects the entire station facility.
$root refers to the root DOM element of the entire Alpine component.
The entire white-background component is the "Facility". Click a button to affect it.
<!-- 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');
}