x-ref for creating HTML element references in Alpine.js

We are going to learn about another feature that would be the x-ref that allows us, as its name indicates, to reference an HTML element in a certain way. In other words, it is the same as placing the document ElementById or querySelector or the 10 that exist in javascript:

document.querySelector(".claseEjemplo")

But it would be the Alpine way, its use is simple, we simply put a label on it, that is, as if it were the ID, the class, the name, a custom attribute, whatever you want, and from here we reference it in the following way, always remember that references to dollars are common in this type of frameworks:

<div x-data="{text:'Hello Alpine!'}">
    <input type="text" x-model="text">
    <p x-text="text"></p>
    <span class="classExample" x-ref="textRef">Text Example</span>
    <button @click="$refs.textRef.innerText=text">Click!</button>
    <button @click="console.log($refs.textRef)">Click!</button>
</div>

And it is to make a separation between what would be the name of our variables that we usually or never put a dollar with those that would be as who says of the same framework, that is to say this is a variable but it is defined at the framework level so I put or to make that distinction then we put refed here the name that we have given it in this example is textRef and here we access its attributes functions everything else everything that is the javascript API which in this case is the property called innerText which is to either get the text or to set a text. Now we are going to make a more complete reference in case you don't get it but again it is basically the getElementById cu selector etcetera that we have in javascript all our lives but in this case it is the Alpine way.

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 4d 12:30!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!