+++
title = "hx-target"
description = """
The hx-target attribute in htmx allows you to target a different element for swapping than the one issuing the AJAX
request."""
+++
The hx-target attribute allows you to target a different element for swapping than the one issuing the AJAX
request. The value of this attribute can be:
- A CSS query selector of the element to target.
thiswhich indicates that the element that thehx-targetattribute is on is the target.closest <CSS selector>which will find the closest ancestor element or itself, that matches the given CSS selector (e.g.closest trwill target the closest table row to the element).find <CSS selector>which will find the first child descendant element that matches the given CSS selector.nextwhich resolves to element.nextElementSiblingnext <CSS selector>which will scan the DOM forward for the first element that matches the given CSS selector. (e.g.next .errorwill target the next element witherrorclass — note this scans the whole DOM forward, not just siblings)previouswhich resolves to element.previousElementSiblingprevious <CSS selector>which will scan the DOM backwards for the first element that matches the given CSS selector. (e.g.previous .errorwill target the previous element witherrorclass — note this scans the whole DOM backward, not just siblings)
Here is an example that targets a div:
<div>
<div id="response-div"></div>
<button hx-post="/register" hx-target="#response-div" hx-swap="beforeend">
Register!
</button>
</div>The response from the /register url will be appended to the div with the id response-div.
This example uses hx-target="this" to make a link that updates itself when clicked:
<a hx-post="/new-link" hx-target="this" hx-swap="outerHTML">New link</a>hx-targetis inherited and can be placed on a parent element