htmx Tutorial · Making Requests · Lesson 8 of 30
Swapping: hx-swap
Control how the response goes into the target: inner or outer HTML, before or after, delete, none, plus timing and scrolling.
Swap styles
hx-swap |
What happens |
|---|---|
innerHTML (default) |
replace the content of the target |
outerHTML |
replace the whole target element |
textContent |
put the response in as plain text (no HTML parsing) |
beforebegin |
insert before the target, as a sibling |
afterbegin |
insert at the start of the target's content |
beforeend |
insert at the end of the target's content (append) |
afterend |
insert after the target, as a sibling |
delete |
remove the target, whatever the response |
none |
don't swap anything (the request still runs; response headers still work) |
<ul id="list"><li>First item</li></ul>
<button hx-get="/item" hx-target="#list" hx-swap="afterbegin">Add at the top</button>
<button hx-get="/item" hx-target="#list" hx-swap="beforeend">Add at the bottom</button>
<button hx-get="/item" hx-target="#list" hx-swap="innerHTML">Replace all</button>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
let n = 1;
server.get("/item", () => `<li>New item ${++n}</li>`);
</script>
Modifiers
Add modifiers after the style, separated by spaces:
swap:500ms: wait before swapping (gives a "fade out" CSS animation time to run).settle:500ms: wait before settling (for "fade in" animations).scroll:bottom/scroll:top: scroll the target after swapping, useful in chat windows.show:top: scroll the page so the target is visible.transition:true: use the browser's View Transitions API for the swap.
<div id="chat" style="height:110px;overflow:auto;border:1px solid #ccc;padding:4px">
<p>Welcome to the chat.</p>
</div>
<button hx-post="/message" hx-target="#chat" hx-swap="beforeend scroll:bottom">Send a message</button>
<button hx-post="/message" hx-target="#chat" hx-swap="delete">Clear chat (delete)</button>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
let m = 0;
server.post("/message", () => `<p>Message number ${++m}</p>`);
</script>
Test yourself
Which hx-swap adds the response to the end of a list without removing the existing items?
beforeendinnerHTMLouterHTMLafterend
Show answer
Answer: beforeend
beforeend appends inside the target; afterend would insert after the list itself.