Understanding $el, $refs, and $root
$el refers to the DOM element the Alpine directive is on.
Analogy: When you poke a fish, only that specific fish reacts. It doesn't know about other fish or the tank as a whole.
Click a Fish!
Activity Log:
No activity yet...
<div @click="interactWithFish($el)">🐠</div>
<script>
interactWithFish(el) {
// 'el' is the clicked div
el.classList.add('highlight');
// ...
}
</script>
$refs provides access to specifically named DOM elements within the component.
Analogy: You can drop food into a specific, named section of coral, causing a reaction only in that area.
Feed a Coral Section
Activity Log:
No activity yet...
<div x-ref="anemone">🪸</div>
<button @click="feedCoral('anemone')">Feed</button>
<script>
feedCoral(name) {
// access the div using this.$refs
let coralEl = this.$refs[name];
coralEl.classList.add('fed');
}
</script>
$root refers to the root DOM element of the Alpine component (`x-data`).
Analogy: An action that affects the entire tank environment, like cleaning the water. All contents are inside the affected tank.
Activity Log:
No activity yet...
<div x-data :class="{'dirty':isDirty}">
<!-- Any button inside can trigger this -->
<button @click="clean($root)">Clean</button>
</div>
<script>
clean(rootEl) {
// 'rootEl' is the main x-data div
rootEl.classList.remove('dirty');
}
</script>