Alpine.js: $el, $refs, & $root

Understanding the Core Magic Variables with a Golf Course Analogy

Course Event Log

$el

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.

Interactive Demo

Each button is a separate Alpine component. Clicking one only affects that specific button ("hole").

Code Example

<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.

$refs

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.

Interactive Demo

Use the control panel to interact with named features on the course.

Control Panel

Clubhouse
Water Hazard

Code Example

<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>

$root

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.

Interactive Demo

Trigger course-wide events. Notice how the entire card's appearance changes.

Course Status:

Code Example

<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>

Summary: Which one to use?

$el

Use when a component needs to change something about itself. Good for self-contained toggles or state indicators.

Analogy: Playing the current hole.

$refs

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.

$root

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.