--- title: "hx-upsert" description: "Update or insert elements by ID for dynamic lists" category: "Swap behaviors" icon: "icon-[mdi--update]" keywords: ["upsert", "swap", "list", "update", "insert"] --- The `upsert` extension adds a new swap style that intelligently updates existing elements by ID and inserts new ones, while preserving elements not in the response. This is particularly useful for maintaining dynamic lists where you want to update specific items without replacing the entire container. ## Installing ```html ``` ## Usage Use [`hx-swap`](/reference/attributes/hx-swap)`="upsert"` to apply the upsert behavior: ```html
Original Item 1
Original Item 2
``` When the server responds with: ```html
Updated Item 2
New Item 3
``` The result will be: ```html
Original Item 1
Updated Item 2
New Item 3
``` ## How It Works The upsert swap style: 1. **Updates** elements with matching IDs (replaces their outerHTML) 2. **Inserts** new elements that don't have matching IDs 3. **Preserves** existing elements not present in the response ## Configuration ### Sorting Add `sort` to maintain elements in ascending order by ID: ```html
``` Use `sort:desc` for descending order: ```html
``` ### Custom Key Attribute Use `key:attr` to sort by a different attribute: ```html
High Priority
Low Priority
``` ### Prepend Unkeyed Elements By default, elements without IDs are appended. Use `prepend` to insert them at the beginning: ```html
``` ### Combined Modifiers ```html
``` ## Using with [``](/docs#partials-hx-partial) You can use `` with `hx-swap="upsert"` for targeted upserts in a single response: ```html
Updated main content
Updated Item 2
New Item 5
``` ## Limitations - Only elements with `id` attributes can be matched and updated - IDs must be unique across the entire document - Sorting uses numeric-aware `localeCompare`, which may have performance implications for very large lists