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

Using a Web Browser analogy.

Action Log

  • No actions yet. Interact with the demos below.

$el : The Active Tab

An element referencing itself. Like a browser tab that knows its own content and can change its own title.

Click the "tab" to change its state.

Code Example:

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

$refs : Bookmarked Sites

Accessing other specific elements from one place. Like a bookmark bar that can activate any bookmarked site.

Content for Site A
Content for Site B
Content for Site C

Code Example:

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

// In JS
this.$refs.siteA.classList.add(...)

$root : The Browser Window

Accessing the component's top-level element. Like a setting that changes the theme of the entire browser window.

This button will affect the entire demo area.

The component root is outlined in green for clarity.

Code Example:

<div x-data="myComponent">
  <button @click="toggleTheme()">
</div>

// In JS
toggleTheme() {
  this.$root.classList.toggle('dark');
}