Morph Plugin (Alpine.morph)

Smoothly morph one DOM tree into another – great for live previews.

Morph Plugin

The @alpinejs/morph plugin provides the Alpine.morph() function, which updates an existing DOM tree to match a new HTML string while preserving element state and focus. It's useful for hot‑module replacement, live previews, or updating HTML fetched from a server.

Installation

Code
npm install @alpinejs/morph

import morph from '@alpinejs/morph'
Alpine.plugin(morph)

Basic Usage

Code
const container = document.getElementById('preview')
const newHtml = '<div><p>Updated content</p></div>'
Alpine.morph(container, newHtml)

When to Use

Use Alpine.morph() when you fetch new HTML from the server and want to seamlessly update a portion of the page without losing Alpine component state.

💡 Tip

Morph uses a patching algorithm similar to morphdom. It's smart enough to preserve Alpine components and their state during the update.

Helpful? Share this page!↑ Back to top