htmx Tutorial · User Feedback · Lesson 14 of 30
Updating Several Places: Out-of-Band Swaps
Update more than one part of the page from a single response with hx-swap-oob.
The problem
You add an item to a cart. The list should get the new item, and the cart counter in the header should change. One request, two places to update.
hx-swap-oob
Any element in the response with hx-swap-oob="true" and an id is taken out of the response and swapped
"out of band" into the element with the same id, wherever it is on the page. The rest of the response goes to the
normal target:
<header>Cart: <span id="cart-count">0</span> items</header>
<button hx-post="/cart" hx-target="#items" hx-swap="beforeend">Add a book</button>
<ul id="items"></ul>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
let count = 0;
server.post("/cart", () => {
count++;
return `<li>Book #${count}</li>
<span id="cart-count" hx-swap-oob="true">${count}</span>`;
});
</script>
Other OOB swap styles
hx-swap-oob accepts the usual swap styles, optionally with a selector:
hx-swap-oob="true": replace the element with the same id (outerHTML).hx-swap-oob="innerHTML": replace only its content.hx-swap-oob="beforeend:#notifications": append to another element.
<button hx-post="/save" hx-target="#doc-status">Save document</button>
<span id="doc-status">Not saved</span>
<ul id="notifications"></ul>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
server.post("/save", () => `Saved at ${new Date().toLocaleTimeString()}
<li hx-swap-oob="beforeend:#notifications">Backup created</li>`);
</script>
Tip: an OOB element for a table row must be wrapped in a <template> in the response, because browsers don't
allow a <tr> outside a table while parsing.
Test yourself
What does an element in a response need so htmx swaps it out of band?
An id and hx-swap-oobA class of htmx-oobTo be the first element in the responseA data-target attribute
Show answer
Answer: An id and hx-swap-oob
htmx finds the page element with the same id and swaps it there.