Alpine.js in the Forest

Demonstrating $el, $refs, and $root with a forest ecosystem analogy.

Ranger's Log

$el: A Single Tree

$el refers to the current DOM element. Actions only affect the tree you interact with.

<button @click="inspectTree($el)">...</button>

// In component:
inspectTree(treeElement) {
  // Reset others first
  this.trees.forEach(t => t.inspected = false);

  // Mark this one as inspected visually
  treeElement.parentElement.classList.add(...)

  // Update a log
  Alpine.store('logStore').add('$el: Inspected a tree.');
}

$refs: Named Wildlife Areas

$refs lets you access specific, named elements from anywhere in the component. Useful for remote control.

🐻 Bear Cave: Waiting for a report...
🦅 Eagle's Nest: Waiting for a report...

Ranger's Station

<div x-ref="bearCave">...</div>
<button @click="checkWildlife('bearCave')">...</button>

// In component:
checkWildlife(area) {
  this.$refs[area].style.transform = 'scale(1.05)';
  this.wildlife[area].status = 'All clear!';
}

$root: The Entire Forest

$root refers to the component's root element. Use it to make changes that affect the entire component boundary.

Change the forest's season, affecting the entire container's appearance.

<div x-data="forestEcosystem">
  <button @click="changeSeason('winter')">...</button>
</div>

// In component:
changeSeason(season) {
  // Remove all season classes
  this.$root.classList.remove(...)
  // Add the new season class
  this.$root.classList.add(`season-${season}`);
}