Targets and swaps

Use relative targets

Build reusable controls with this, closest, find, next, and previous instead of unique ids for every row.

Relative targets let repeated components describe their local structure without generating a unique global ID for every row:

<li>
  <span>Send invoice</span>
  <button
    hx-delete="/tasks/42"
    hx-target="closest li"
    hx-swap="delete">
    Delete
  </button>
</li>

HTMX supports several extended selectors:

  • this targets the element carrying the attribute
  • closest <selector> walks through ancestors, including the element itself
  • find <selector> finds the first matching descendant
  • next and previous choose a sibling
  • next <selector> and previous <selector> scan forward or backward

The selector is resolved from the triggering element, including when an inherited attribute was declared on a parent. That detail matters for find: the trigger’s descendants may differ from the parent’s descendants.

Use relative selectors for a stable component relationship such as “this row” or “the next error message.” Use an ID when the target is a page-level region unrelated to the trigger’s local tree.

Duplicate the row and confirm both buttons update only their own copy.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →