Understanding `$el`, `$refs`, and `$root` with a restaurant analogy.
No actions recorded yet. Interact with the demos below.
Analogy: A chef's personal workspace. $el gives direct access to the component's root element, allowing it to modify itself.
Chef Antoine's Station
Status:
<div x-data="chefStation">
<!-- ... -->
</div>
Alpine.data('chefStation', () => ({
status: 'Tidy',
clean() {
this.status = 'Immaculate';
// this.$el refers to the div above
this.$el.classList.add('bg-green-100');
},
// ...
}))
Analogy: Using specific, named equipment from anywhere in the kitchen. $refs lets you access any element marked with x-ref from within the component.
Control Panel
Mixer
OffOven
Off
<div x-data="kitchen">
<button @click="operate('mixer')">
Use Mixer
</button>
<div x-ref="mixer">...</div>
</div>
Alpine.data('kitchen', () => ({
operate(name) {
// this.$refs.mixer refers to the div
const el = this.$refs[name];
el.classList.add('bg-blue-200');
}
}))
Analogy: A kitchen-wide event, like a fire alarm. $root refers to the top-level element of the current component, affecting its entire scope.
Kitchen Management
Overall Status:
Notice the red pulsing border on the entire kitchen area when the alarm sounds.
<div x-data="kitchen">
<!-- Deeply nested button -->
<button @click="soundAlarm()">
Alarm
</button>
</div>
Alpine.data('kitchen', () => ({
soundAlarm() {
// this.$root is the component's top div
this.$root.classList.add('emergency');
}
}))