Understanding the Core Magic Variables with a Golf Course Analogy
No events yet. Interact with the demos below.
:
The Current Hole
$el refers to the component's own root DOM element. It’s like focusing only on the hole you are currently playing.
Each button is a separate Alpine component. Clicking one only affects that specific button ("hole").
<div x-data="holeComponent">
<button @click="playHole()">Play</button>
</div>
<script>
Alpine.data('holeComponent', () => ({
playHole() {
// this.$el is the <div>
this.$el.querySelector('button')
.classList.add('played');
this.$el.querySelector('button')
.innerText = 'Played';
}
}))
</script>
This demo uses multiple tiny components to show how $el is always scoped to its own element.
Named Features on the Course
$refs lets you access other specific, named elements within your component. It's like having a map to find the "Clubhouse" or the "18th Green" from anywhere.
Use the control panel to interact with named features on the course.
<div x-data="refsDemo">
<button @click="visitClubhouse()">Visit</button>
<div x-ref="clubhouse">...</div>
</div>
<script>
Alpine.data('refsDemo', () => ({
visitClubhouse() {
// this.$refs.clubhouse is the div
this.$refs.clubhouse.classList
.add('visited');
}
}))
</script>
The Entire Course
$root refers to the top-most DOM element of the component. It's like a weather event that affects the entire golf course boundary at once.
Trigger course-wide events. Notice how the entire card's appearance changes.
Course Status:
<div x-data="rootDemo">
<button @click="rainDelay()">Rain</button>
</div>
<script>
Alpine.data('rootDemo', () => ({
rainDelay() {
// this.$root is the main component div
this.$root.classList.add('rainy');
}
}))
</script>
Use when a component needs to change something about itself. Good for self-contained toggles or state indicators.
Analogy: Playing the current hole.
Use when you need to reach out and manipulate a specific, named child element from your component's logic.
Analogy: Finding a named feature on the course.
Use when you need to manipulate the entire boundary of your component. Useful for global state indicators on the component itself.
Analogy: An event affecting the entire course.