點燈坊

失くすものさえない今が強くなるチャンスよ

Using $el to Access the Current Element

Sam Xiao's Avatar 2022-01-27

Instead of using x-ref and $refs to access the current element, Alpine also provides $el for conciseness.

Version

Alpine 3.9

$el

el000

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 component
  • x-init : run expressions on initialization phase of the component
  • $el : retrieve the current DOM element

Conclusion

  • By using $el, we don’t have to use x-ref and $refs anymore

Reference

Alpine, $el