htmx 4.0 is under construction — migration guide

hx-target

Specify target element for swap

The hx-target attribute specifies where to insert the response content.

Defaults to this (which represents the element making the request).

Value

this

Target the element itself.

<a hx-post="/new-link" hx-target="this" hx-swap="outerHTML"> New link </a>

The link updates itself when clicked.

Extended Selectors

Use any extended selector to target elements:

  • CSS selectors: #results, .container, [data-target]
  • closest <selector> - nearest ancestor (or the element itself) matching selector
  • find <selector> - first child descendant matching selector
  • findAll <selector> - all child descendant elements matching selector
  • next - next sibling element
  • next <selector> - scan forward for selector
  • previous - previous sibling element
  • previous <selector> - scan backward for selector

See the full extended selectors guide.

Common Patterns

Target a specific element

<button hx-post="/register" hx-target="#response-div"> Register </button> <div id="response-div"></div>

Update parent container

<div class="card"> <button hx-get="/refresh" hx-target="closest .card"> Refresh Card </button> </div>

Update sibling element

<button hx-get="/data" hx-target="next .results">Load</button> <div class="results"></div>

Update child element

<div hx-get="/user" hx-target="find .status"> <span class="status">Loading...</span> </div>