Alpine.js in the Living Room

Demonstrating $el, $refs, and $root.

Global Controls

Reset the entire demonstration to its initial state.

Action Log

Waiting for an action...

$el: The Current Furniture

$el refers to the current DOM element. It's like a piece of furniture knowing about itself. An action performed on the item affects that item directly.

The Coffee Table

View Code
<!-- The button acts on its sibling's parent -->
<div x-ref="table">...</div>
<button @click="polishTable($refs.table)">
  Polish this Table
</button>

<script>
  // In Alpine.data component...
  polishTable(tableElement) {
    // We use $el (passed as tableElement)
    // to directly manipulate the element.
    tableElement.classList.add('bg-yellow-100');
    this.tableIsPolished = true;
  }
</script>

$refs: The Named Electronics

$refs gives you access to specific elements you've named with x-ref. It's like a universal remote that can control any electronic device by its name (TV, Sound System).

Remote Control
📺 TV:
🔊 Sound:
View Code
<!-- The button can be anywhere in the component -->
<button @click="toggleTv()">Toggle TV</button>

<!-- The target element is named with x-ref -->
<div x-ref="tv">TV Status</div>

<script>
  // In Alpine.data component...
  toggleTv() {
    // We use $refs to get the element by name.
    this.$refs.tv.classList.toggle('bg-green-200');
    this.tvIsOn = !this.tvIsOn;
  }
</script>

$root: The Entire Room

$root refers to the top-level DOM element of the component (the element with x-data). It's like a command that affects the entire room, such as starting a robot vacuum.

Room Controls

This action will apply a style to the entire component box (the dotted-line container for all three demos).

Room Status:

View Code
<div x-data="livingRoom"> <!-- This is $root -->
  ...
  <button @click="cleanRoom()">Clean Room</button>
  ...
</div>

<script>
  // In Alpine.data component...
  cleanRoom() {
    // We use $root to affect the component's
    // main container element.
    this.$root.classList.add('cleaning-animation');
    this.roomIsBeingCleaned = true;
  }
</script>