Using x-ref in Alpine.js
giving names to DOM elements in Alpine.js
// updated 2025-09-29 12:23
If we have HTML with a DOM element such as a <div> tag, we might refer it to using an id attribute but to make it less confusing, we can use x-ref on that tag and then refer to it using an Alpine "magic" keyword called $refs:
So, to access a DOM element from another element using the $refs magic, we would use this syntax:
1$refs.theXRef...where theXRef is the value of the x-ref attribute of the "reffed" DOM element
(i.e. replace textBlock in the above Codepen with the appropriate x-ref value!)