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

Understanding DOM access through a Science Museum analogy.

Museum Activity Log

No activity yet. Interact with the demos below!

$el: The Current Exhibit

The $el magic property refers to the DOM element the Alpine directive is on. It's like focusing on the single exhibit you're currently interacting with.

Exhibit Hall

Code Example

Clicking the panel calls a method, passing its own element ($el) for manipulation.

<div @click="highlightExhibit($el)">...</div>

$refs: The Named Displays

The $refs magic property gives you access to specific elements within your component that you've "named" with the x-ref directive. Think of this as a control panel for all named displays in an exhibit hall. You can target a specific display by its name.

Display Control Panel


Tyrannosaurus Rex

A magnificent fossil display.

Apollo 11 Capsule

A journey to the moon.

Code Example

Name elements with x-ref, then access them via $refs.

<!-- The named display -->
<div x-ref="dinosaurDisplay">...</div>

<!-- The button to control it -->
<button @click="$refs.dinosaurDisplay.scrollIntoView()">
    Go to Dino
</button>

$root: The Entire Museum

The $root magic property refers to the root DOM element of the entire Alpine component. This is like triggering a museum-wide event, such as a closing announcement or a special lighting theme, that affects the whole building (the component boundary).

Museum-Wide Event Controls

Internal Exhibit Area

These buttons are nested deep inside the "museum" component, but they can affect the entire component's root element.

Code Example

A button inside the component can add a class to its top-level element.

<div x-data="{...}">
    <!-- ... other elements ... -->
    <button @click="$root.classList.add('emergency-styles')">
        Trigger Emergency
    </button>
</div>