htmx: Targets

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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!