Alpine.js: $el, $refs, $root

Understanding Magic Properties with a Home Office Analogy

$el: The Current Device

$el refers to the specific DOM element the Alpine directive is attached to. It's like pointing to the device you are currently using.

Status:

<button @click="focusOnDevice($el)">...</button>

$refs: Named Supplies

$refs lets you access any element inside your component marked with x-ref. It's like having a control panel for specific, named supplies at your desk.

Office Supplies:

🖥️ Monitor
⌨️ Keyboard
💡 Desk Lamp

Control Panel:

Status:

<div x-ref="monitor">...</div> <button @click="toggleSupply('monitor')">...</button> // In JS: this.$refs.monitor

$root: The Entire Office

$root refers to the root element of your Alpine component (the one with x-data). It's like controlling the entire office environment itself.

Status:

<div x-data="...">   <button @click="$root.classList.toggle('dark')">...</button> </div> // In JS: this.$root

Office Action Log

No actions yet. Interact with the demos above.