Use htmx hx-get to Load a Fragment on Button Click – A Step‑by‑Step Task Guide
Learn how to use htmx’s hx-get to fetch an HTML fragment and replace a target element on a button click. This guide covers prerequisites, implementation, verification, and recovery options for reliable, partial page updates.
29 Jun 2026, 07:41 UTC

Problem & Desired Outcome
You need to update a portion of a page without a full reload when a user clicks a button. The goal is to fetch a small HTML fragment from the server and inject it into a target element, keeping the rest of the page intact.
Prerequisites
- htmx library loaded in the page (CDN or bundled)
- Server endpoint that returns a valid HTML fragment (no full page wrapper)
- Target element present in the initial DOM (e.g.,
<div id="container"></div>) - Browser with JavaScript enabled
- Knowledge of the HTTP GET request flow and basic console debugging
Step‑by‑Step Procedure
- Load htmx
<script src="https://unpkg.com/htmx.org@1.9.3"></script>Include the script in the
<head>or before the closing</body>tag. The version 1.9.3 is used here; adjust according to your project. - Define the target element
<div id="container">Initial content</div>This element will receive the new HTML fragment.
- Add the button with htmx attributes
<button hx-get="/partial" hx-target="#container" hx-trigger="click">Load Fragment</button>hx-get– URL to request.hx-target– CSS selector of the element to replace.hx-trigger– Event that initiates the request; here it is the standardclick.
- Server side
Ensure the endpoint
/partialreturns a 200 OK with an HTML fragment, e.g.:<div>This is the new fragment loaded via htmx.</div>Set proper
Content-Type: text/htmland, if cross‑origin, appropriate CORS headers. - Optional – Add error handling
To display a fallback UI when the request fails, use
hx-on:errorto inject a message:<button hx-get="/partial" hx-target="#container" hx-trigger="click" hx-on:error="#container.innerHTML='Error loading content.'">Load Fragment</button>
Expected Checks
- Open DevTools → Network tab. After clicking the button, a GET request to
/partialshould appear with status 200. - Check the Response tab: the body should contain the fragment without full page markup.
- Inspect the
#containerelement after the click: its innerHTML should match the response. - Confirm no full page reload by observing the document title or URL unchanged.
- Open the Console for errors. There should be no htmx‑related exceptions.
Recovery Options
- Retry logic – Use
hx-on:errorto trigger a retry button or automatically re‑send the request after a delay.<button hx-get="/partial" hx-target="#container" hx-trigger="click" hx-on:error="setTimeout(()=>this.click(),2000)">Load Fragment</button> - Graceful fallback – Provide a static fallback content inside
#containerthat remains if the request never succeeds. - Server‑side validation – Return a 204 No Content if nothing to update, and handle it client‑side by ignoring the update.
Limitations & Practical Checks
- htmx 1.9+ changed the attribute names for non‑click triggers; older docs may reference
hx-trigger="click"differently. Verify your version’s docs. - If the target element is removed from the DOM before the response arrives, htmx silently discards the update. Ensure the element stays in place or handle
htmx:afterSwapevents to re‑attach if needed. - Missing CORS headers on the server will prevent the request from completing in cross‑origin scenarios, leading to silent failures. Test with
curl -Ito confirm headers. - When debugging, remember that htmx uses
innerHTMLreplacement by default. If you need to preserve event listeners on existing child nodes, usehx-swap="outerHTML"or custom swap strategies.
Practical Verification Script
You can run a quick check in the console after the click:
const container = document.getElementById('container');
console.assert(container.innerHTML.trim() !== '', 'Container should not be empty after hx-get');
Repeat the click to ensure consistent updates.
Conclusion
By following this guide, you can reliably fetch and inject HTML fragments with htmx’s hx-get on button clicks, verify the operation, and handle errors gracefully. The approach keeps the user experience smooth by avoiding full page reloads while maintaining a declarative, minimal‑code workflow.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.