Skip to content

$refs

$refs is a magic property that can be used to retrieve DOM elements marked with x-ref inside the component. This is useful when you need to manually manipulate DOM elements. It's often used as a more succinct, scoped, alternative to document.querySelector.

html
<button @click="$refs.text.remove()">Remove Text</button>
 
<span x-ref="text">Hello 👋</span>

When the <button> is pressed, the <span> will be removed.

Access x-model methods

Alpine exposes under-the-hood utilities for getting and setting properties bound with x-model. You can access these utilities through a property called _x_model on the x-modeled element.

_x_model has two methods to get and set the bound property:

  • el._x_model.get() (returns the value of the bound property)
  • el._x_model.set() (sets the value of the bound property)
html
<div x-data="{ username: 'calebporzio' }">
    <div x-ref="div" x-model="username"></div>
 
    <button @click="$refs.div._x_model.set('phantomatrix')">
        Change username to: 'phantomatrix'
    </button>
 
    <span x-text="$refs.div._x_model.get()"></span>
</div>

Limitation

In Alpine.js V2, it was possible to bind $refs to elements dynamically, like seen below:

html
<template x-for="item in items" :key="item.id" >
    <div :x-ref="item.name">
    some content ...
    </div>
</template>

However, in V3, $refs can only be accessed for elements that are created statically. So for the example above: if you were expecting the value of item.name inside of $refs to be something like Batteries, you should be aware that $refs will actually contain the literal string 'item.name' and not Batteries.