htmx interview question · Most asked
What is hx-target, and what relative selectors does it support?
Summary
hx-target chooses where the response goes; by default it's the element that made the request. It takes a CSS selector or extended selectors: this, closest <sel>, next, next <sel>, previous, previous <sel> and find <sel>.
Longer Answer
Relative selectors let the same markup work for every item in a list. A delete button with hx-target="closest tr" removes its own row without unique ids. In htmx 2 hx-target is inherited, so it can sit once on a parent; in htmx 4 inheritance must be explicit with hx-target:inherited.
Code Example
<tr><td>Ada</td><td><button hx-delete="/contacts/1" hx-target="closest tr" hx-swap="outerHTML">Delete</button></td></tr>
Key Points
- Default: the requesting element.
- Any CSS selector.
- this, closest, next, previous, find.
- Inherited in htmx 2.
Deep dive: htmx Tutorial: Targets: hx-target
More most-asked htmx questions
- What security risks are specific to htmx, and how do you mitigate them?
- How does htmx compare with React or Vue?
- What is htmx?
- What do hx-get, hx-post, hx-put, hx-patch and hx-delete do, and how are values sent?
- What swap styles does hx-swap support?
- How does hx-trigger work? Give examples of modifiers and special triggers.
- How do you handle form validation errors with htmx?
- Explain the htmx request lifecycle.