Under The Hood
frontend htmx HTMX 1.x / 2.x

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

react equivalent
Conditional JSX rendering replacing nodes or arrays of items.

Legacy vs modern

Append vs Replace with hx-swap

`innerHTML` replaces the entire container; `hx-swap="beforeend"` appends new items to an existing list.

before → after
Destructive innerHTML Replacement
<div hx-get="/more-items" hx-target="#list"> // ❌ Overwrites entire list with new items
Infinite Scroll Append via beforeend
<div hx-get="/more-items" hx-target="#list" hx-swap="beforeend"> // ✅ NEW: Appends cleanly

Interview 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.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.