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 selectornext <CSS selector>to find the closest next element that matches the CSS selectorprevious <CSS selector>to find the closest previous element that matches the CSS selectorfind <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 |