Understanding $el, $refs, and $root
Log is empty. Interact with the demos below.
$el refers to the current DOM element. A fish knows about itself and can change its own properties directly.
<!-- The button is inside the fish component -->
<button @click="$el.classList.toggle('bg-orange-400')">
Change My Color
</button>
$refs lets you access any element marked with x-ref from anywhere inside the component. It's like a control panel that can target specific, named coral reefs.
<!-- The element to be referenced -->
<div x-ref="brainCoral">...</div>
<!-- The button that references it -->
<button @click="$refs.brainCoral.classList.add('glowing')">
Light Up
</button>
$root refers to the root element of the Alpine component. Any element inside the tank can affect the entire tank environment, like changing the water temperature.
Tank Controls
<div x-data> <!-- This is the root -->
<button @click="$root.classList.add('warm-bg')">
Change Temp
</button>
</div>
| Concept | Analogy | Scope | Use Case |
|---|---|---|---|
| $el | A fish changing its own color. | The element the directive is on. | Self-manipulation (e.g., getting its own attributes, toggling a class on itself). |
| $refs | A central panel lighting up a specific, named coral. | Any element with an `x-ref` within the component. | Accessing specific, distant elements for targeted manipulation (e.g. focusing an input). |
| $root | Changing the water temperature for the entire tank. | The component's top-level element (with `x-data`). | Affecting the entire component's container (e.g., changing its background, adding a "loading" state class). |