htmx Tutorial · Making Requests · Lesson 7 of 30
Targets: hx-target
Put the response somewhere other than the triggering element using CSS selectors and relative selectors like closest and next.
The default target
By default, htmx puts the response inside the element that made the request. Use hx-target to choose another
element.
Ways to name the target
| Value | Target |
|---|---|
#result (any CSS selector) |
the first element matching the selector |
this |
the element itself |
closest tr |
the nearest ancestor (or itself) matching tr |
next .panel |
the next element after this one matching .panel |
previous .panel |
the previous element matching .panel |
find .count |
the first child element matching .count |
next / previous |
the next or previous sibling element |
Relative selectors such as closest let one piece of markup work in a list of many: every row's button targets
its own row, no unique ids needed.
<table>
<tr><td>Ada</td><td class="status">Offline</td><td><button hx-get="/ping/Ada" hx-target="closest tr" hx-swap="outerHTML">Ping</button></td></tr>
<tr><td>Alan</td><td class="status">Offline</td><td><button hx-get="/ping/Alan" hx-target="closest tr" hx-swap="outerHTML">Ping</button></td></tr>
</table>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
server.get("/ping/:name", (req) => `<tr><td>${server.escape(req.params.name)}</td><td class="status">Online</td><td>✓</td></tr>`);
</script>
Inheritance
In htmx 2, hx-target (and most other attributes) is inherited: put it on a parent and every htmx element inside
uses it, unless it sets its own.
<div hx-target="#panel">
<button hx-get="/tab/a">Profile</button>
<button hx-get="/tab/b">Settings</button>
</div>
<div id="panel">Choose a tab.</div>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
server.get("/tab/a", () => "<h3>Profile</h3><p>Name: Ada</p>");
server.get("/tab/b", () => "<h3>Settings</h3><p>Theme: dark</p>");
</script>
Test yourself
A delete button sits inside a <tr> in a long table. Which target removes or updates just that row?
closest tr#rowthisnext tr
Show answer
Answer: closest tr
closest tr finds the button's own row, so the same markup works for every row.