hx-swap: innerHTML, outerHTML, beforebegin, afterend, and delete Strategies
- Last updated
- Prerequisites:
- HTML DOM insertion methods
- HTMX hx-get/hx-post basics
- htmx
- hx-swap
- dom
- outerHTML
- innerHTML
- morphing
Read at your depth
The practical view
`hx-swap` controls how the returned HTML response is placed into the DOM relative to `hx-target`. Default is `innerHTML` (replaces children). Common strategies: `outerHTML` (replaces target element itself), `beforebegin` (inserts before target), `afterbegin` (prepends inside target), `beforeend` (appends inside target), `afterend` (inserts after target), and `delete` (removes target). You can also control scroll behavior via `hx-swap="innerHTML scroll:top"`.
The same idea in other frameworks
Conditional JSX rendering replacing nodes or arrays of items.`ViewContainerRef.createEmbeddedView()` with insertion indices.Dynamic component swapping or `v-html` insertions.`hx-swap="innerHTML | outerHTML | beforebegin | afterbegin | beforeend | afterend | delete"`.Legacy vs modern
Append vs Replace with hx-swap
`innerHTML` replaces the entire container; `hx-swap="beforeend"` appends new items to an existing list.
<div hx-get="/more-items" hx-target="#list"> // ❌ Overwrites entire list with new items<div hx-get="/more-items" hx-target="#list" hx-swap="beforeend"> // ✅ NEW: Appends cleanlyInterview gotchas
Context
Interviewers test your precision with DOM element replacement boundaries.
The mechanical answer
`innerHTML` replaces the *children* of the target element while keeping the target element's opening and closing tag intact. `outerHTML` replaces the *target element itself* along with its children, substituting it entirely with the incoming HTML response.
Trap
If using `hx-swap="outerHTML"`, the incoming server response must include the outer container element (with attributes and IDs) if subsequent HTMX interactions on that element are expected.
Context
Checks understanding of HTMX CSS transition swap timing modifiers.
The mechanical answer
Use the `swap` timing modifier: `hx-swap="delete swap:500ms"`. When triggered, HTMX adds the `.htmx-swapping` CSS class to the element, waits 500ms (allowing a CSS `opacity: 0; transform: scale(0.8)` transition to play), and then removes the element from the DOM.
Trap
Without specifying `swap:500ms`, `hx-swap="delete"` removes the element instantly, preventing any CSS exit transitions from playing.