| 1 | --- |
| 2 | title: "hx-preserve" |
| 3 | description: "Preserves the element during swaps" |
| 4 | --- |
| 5 | |
| 6 | The `hx-preserve` attribute allows you to keep an element unchanged during HTML replacement. |
| 7 | Elements with `hx-preserve` set are preserved by `id` when htmx updates any ancestor element. |
| 8 | You *must* set an unchanging `id` on elements for `hx-preserve` to work. |
| 9 | The response requires an element with the same `id`, but its type and other attributes are ignored. |
| 10 | |
| 11 | ## Syntax |
| 12 | |
| 13 | ```html |
| 14 | <div id="video-player" hx-preserve="true">...</div> |
| 15 | ``` |
| 16 | |
| 17 | ## Notes |
| 18 | |
| 19 | * You can use `hx-preserve="true"` or use it as a boolean attribute with just `hx-preserve` |
| 20 | * Some elements cannot unfortunately be preserved properly, such as `<input type="text">` (focus and caret position are |
| 21 | lost), iframes or certain types of videos. To tackle some of these cases we recommend |
| 22 | the [morphdom extension](https://github.com/bigskysoftware/htmx-extensions/blob/main/src/morphdom-swap/README), which |
| 23 | does a more elaborate DOM |
| 24 | reconciliation |
| 25 | * When using [History Support](/docs#history) for actions like the back button `hx-preserve` elements will also have |
| 26 | their state preserved |
| 27 | * Avoid using [`hx-swap`](/reference/attributes/hx-swap) set to `none` with requests that could contain a `hx-preserve` element to |
| 28 | avoid losing it |
| 29 | * `hx-preserve` can cause elements to be removed from their current location and relocated to a new location when |
| 30 | swapping in a partial/oob response |
| 31 | ```html |
| 32 | <div id="new_location"> |
| 33 | Just relocated the video here |
| 34 | <div id="video" hx-preserve></div> |
| 35 | </div> |
| 36 | ``` |
| 37 | * Can be used on the inside content of a [`hx-swap-oob`](/reference/attributes/hx-swap-oob) element |
| 38 | ```html |
| 39 | <div id="notify" hx-swap-oob="true"> |
| 40 | Notification updated but keep the same retain |
| 41 | <div id="retain" hx-preserve></div> |
| 42 | </div> |
| 43 | ``` |
| 44 | * Works with morph swaps (`innerMorph`/`outerMorph`). When the server response includes an element with `hx-preserve`, |
| 45 | htmx stashes the live element before morphing and restores it afterward. The `id` is required for morph the same as |
| 46 | for other swap styles. Note that morph already natively preserves element identity for elements with matching `id`s. |
| 47 | DOM state, focus, and scroll position are maintained without `hx-preserve`. To prevent server updates from changing |
| 48 | an element or its children entirely, use [`hx-morph-skip`](/reference/config/htmx-config-morphSkip) or |
| 49 | [`hx-morph-skip-children`](/reference/config/htmx-config-morphSkipChildren) in your server templates. These work |
| 50 | similarly to `hx-preserve` but are morph-specific and don't always require an `id`. |