Demonstrating $el, $refs, and $root
Log is empty. Interact with the demos below.
Refers to the element the event handler is on. Like a bowler interacting directly with their own lane.
Lane 1
Lane 2
Lane 3
<!-- The button references itself with $el -->
<button @click="waxLane($el)">Wax This Lane</button>
<!-- In Alpine.data -->
waxLane(el) {
const lane = el.closest('.lane');
lane.classList.add('bg-yellow-200', 'border-yellow-400');
// ...
}
Access any element with x-ref from anywhere in the component. Like the front desk controlling specific equipment by name.
<!-- Any element can be named with x-ref -->
<div x-ref="pinsetterRef">...</div>
<!-- In Alpine.data -->
activatePinsetter() {
this.$refs.pinsetterRef.innerText = 'Resetting pins...';
this.$refs.pinsetterRef.classList.add('bg-green-300');
// ...
}
Refers to the root element of the component. Like the manager changing the mode for the entire alley.
The $root is this entire demo's container.
<!-- The root component element -->
<div x-data="bowlingAlley">...</div>
<!-- In Alpine.data -->
startCosmicBowling() {
this.$root.classList.add('bg-gray-900', 'border-purple-500');
this.$root.querySelectorAll('h1, h2, h3, h4, p').forEach(el => {
el.classList.add('text-white');
});
// ...
}