Alpine.js: The Dance Studio

Understanding $el, $refs, and $root

Choreographer's Log

$el: The Current Dancer

Analogy: A dancer interacting with themself.

$el refers to the current DOM element where an event handler is attached. The button below uses $el.parentElement to get a reference to its container (the "dancer") and change its costume.

Dancer Zone

I am the dancer.

Code Example:

<div id="dancerEl">
  <button @click="changeOutfit($el.parentElement)">
    ...
  </button>
</div>

$refs: The Named Mirrors

Analogy: A choreographer calling out specific dancers by the named mirror they are practicing in front of.

$refs provides a way to access specific, named elements from anywhere within the component. You "name" an element with the x-ref directive.

Practice Mirrors

Mirror A
Mirror B
Mirror C

Code Example:

<div x-ref="mirrorA">...</div>

// In the component script:
this.$refs.mirrorA.classList.add(...)

$root: The Entire Studio

Analogy: The studio manager flipping the main switch to change the lighting for the entire studio.

$root refers to the root element of the Alpine component (the one with x-data). This is useful for manipulating the component's main container.

Studio Controls

Notice the background of this whole page section will change.

Code Example:

<div x-data="danceStudio">
  <button @click="toggleStudioLights($root)">
    ...
  </button>
</div>