Targets and swaps

Insert before or after existing content

Append, prepend, or place a returned fragment next to the target without rerendering the entire list.

Adjacent swaps use the same positions as insertAdjacentHTML:

  • beforebegin: before the target itself
  • afterbegin: inside the target, before its first child
  • beforeend: inside the target, after its last child
  • afterend: after the target itself

To append a newly created task:

<form action="/tasks" method="post"
  hx-post="/tasks"
  hx-target="#task-list"
  hx-swap="beforeend">
  ...
</form>

<ul id="task-list"></ul>

The server returns one valid <li>. The list remains and the new row is inserted at its end.

Appending is correct only when the new row is the complete change. If creation also changes sorting, a total, pagination, or an empty-state message, returning the whole list region is simpler and less prone to stale UI.

Also consider concurrent requests. Two responses may arrive in a different order than they were sent. If order matters, synchronize the requests or let the server return the complete authoritative ordering.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →