Instead of using x-ref
and $refs
to access the current element, Alpine also provides $el
for conciseness.
Version
Alpine 3.9
$el
The textbox is focused on page loads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body>
<input x-data x-init="$el.focus()" />
</body>
</html>
Line 10
<input x-data x-init="$el.focus()" />
x-data
: make the current element as a single-element componentx-init
: run expressions on initialization phase of the component$el
: retrieve the current DOM element
Conclusion
- By using
$el
, we don’t have to usex-ref
and$refs
anymore