Understanding $el,
$refs, and
$root through analogy.
No activity yet. Interact with the demos below.
An element referring to itself, like a dancer choosing their own move.
// The dancer element acts on itself using $el
<button @click="el_performMove($el)">
...
</button>
// An Alpine method receives $el as an argument
el_performMove(dancerElement) {
// dancerElement is the button itself
dancerElement.classList.add(...);
}
A controller accessing specific elements by name, like a choreographer using mirrors to direct named dancers.
// Dancers are named with x-ref
<div x-ref="dancerAlex">...</div>
// The controller calls a method with the ref name
<button @click="refs_spotlight('dancerAlex')">
// The method uses $refs to find the named element
refs_spotlight(dancerRefName) {
const dancer = this.$refs[dancerRefName];
dancer.style.transform = 'scale(1.1)';
}
An element accessing its component's root, like a light switch affecting the whole studio.
(This whole box is the component root)
Technician's Booth (nested)
// The component root is the bordered box with x-data
<div x-data="studioRootDemo">
...
<button @click="toggleLights()">
...
</button>
...
</div>
// The method uses $root to access that div
toggleLights() {
// this.$root IS the div with x-data
this.$root.classList.toggle('bg-gray-800');
}