Understanding $el, $refs, and $root using an interactive home office analogy.
$el refers to the DOM element the Alpine directive is on. It's like interacting with the very device you are touching. Click a device to see it become "active".
Active Device: None
<button @click="setActiveDevice($el, 'Laptop')">
💻 Laptop
</button>
$refs lets you access specific elements by name from anywhere in the component. It's like a remote control for named items in your office.
<div x-ref="deskLamp">...</div>
<button @click="toggleLamp()">...</button>
// In JS:
toggleLamp() {
this.$refs.deskLamp.classList.toggle('active');
}
$root refers to the top-level element of the component. It's the master switch that affects the entire office space at once.
<div x-data="office">
<button @click="powerOutage()">...</button>
</div>
// In JS:
powerOutage() {
this.$root.classList.add('power-out');
}