htmx: Targets

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


We used the hx-target attribute to tell htmx where to put the response of the request.

This attribute takes a CSS selector, which is what you’re likely familiar to use in CSS to target an element, for example by id or class.

In our example we had hx-target="#result".

That put the result of the request to the element with the id attribute equal to result

(As a reminder, the difference between id and class is that id attributes must be unique on a page, while class can be repeated multiple times, so you have to handle that case)

This is the simplest usage of hx-target.

You can use hx-target="this" to target “this element we are defining the xh-target attribute on”.

Then we can navigate the HTML elements around or near us with:

  • closest <CSS selector> to find the closest parent that matches the CSS selector
  • next <CSS selector> to find the closest next element that matches the CSS selector
  • previous <CSS selector> to find the closest previous element that matches the CSS selector
  • find <CSS selector> to find the closest child that matches the CSS selector

For example in a project I used hx-target="closest li" in a list with a delete button to delete the entire li (list item) when I clicked the delete button to delete the item.

Lessons in this unit:

0: Introduction
1: Why htmx
2: The core idea of htmx
3: Installing htmx
4: Doing a GET request
5: Swap
6: POST request
7: ▶︎ Targets
8: Loading indicator
9: Confirming actions, and prompts
10: Triggers
11: Request headers
12: Response headers
13: Events
14: Redirect after request
15: Send files using htmx.ajax()
16: Perform something on page load
17: Conditionally hide HTML elements based on HTMX request status
18: htmx + Alpine template tag
19: htmx, include hidden input fields outside of a form
20: htmx trigger request via JS event