| 1 | --- |
| 2 | title: "hx-history-elt" |
| 3 | description: "Marks the element to swap on history restore" |
| 4 | --- |
| 5 | |
| 6 | The `hx-history-elt` attribute marks the element that htmx should swap when restoring a page from |
| 7 | history (back/forward navigation). Only this element is replaced — the rest of the page is left |
| 8 | untouched. |
| 9 | |
| 10 | When a history restore request is made, htmx sends a `GET` request with the |
| 11 | [`HX-History-Restore-Request`](/reference/headers/HX-History-Restore-Request) header. The server |
| 12 | should return a full page response; htmx selects the `hx-history-elt` element from it and swaps it |
| 13 | into the matching element in the current page. |
| 14 | |
| 15 | ## Syntax |
| 16 | |
| 17 | ```html |
| 18 | <main hx-history-elt> |
| 19 | <!-- only this element is replaced on back/forward navigation --> |
| 20 | </main> |
| 21 | ``` |
| 22 | |
| 23 | ## Example |
| 24 | |
| 25 | ```html |
| 26 | <body> |
| 27 | <nav><!-- never replaced --></nav> |
| 28 | |
| 29 | <main hx-history-elt> |
| 30 | <h1>Page 1</h1> |
| 31 | <button hx-get="/page2" hx-target="[hx-history-elt]" hx-push-url="/page2"> |
| 32 | Go to Page 2 |
| 33 | </button> |
| 34 | </main> |
| 35 | </body> |
| 36 | ``` |
| 37 | |
| 38 | The server should detect `HX-History-Restore-Request` and return a full page containing a matching |
| 39 | `hx-history-elt` element: |
| 40 | |
| 41 | ``` |
| 42 | if request.headers["HX-History-Restore-Request"]: |
| 43 | return render_full_page() # includes <main hx-history-elt>...</main> |
| 44 | else: |
| 45 | return render_fragment() # just the inner content |
| 46 | ``` |
| 47 | |
| 48 | ## Notes |
| 49 | |
| 50 | * Only one `hx-history-elt` element should exist in the page at a time |
| 51 | * If no `hx-history-elt` is present, htmx falls back to swapping `<body>` |
| 52 | * The server response must include a `hx-history-elt` element for the select to work; if it is |
| 53 | missing, htmx falls back to a full body swap |
| 54 | * In htmx 2, history was cached in localStorage. In htmx 4, caching has moved to the |
| 55 | [`hx-history-cache`](/docs/extensions/history-cache) extension — `hx-history-elt` works with |
| 56 | both the core re-fetch behavior and the extension's cache restore |