hx-target with a .class selector only swaps the first matching element
Scenario
Every post has a .post-toolbar so users can like the post. When a user clicks the post, it opens a dialog for detail with the same .post-toolbar component.
<div id="post-123" hx-get="/post_detail/123" hx-target="body">
<!-- ... -->
<div class="post-toolbar-123">
<button hx-target=".post-toolbar-123">Like 👍</button>
</div>
</div>
<!-- GET /post_detail/123 -->
<dialog id="post-detail-123">
<!-- ... -->
<div class="post-toolbar-123">
<button hx-target=".post-toolbar-123">Like 👍</button>
</div>
</dialog>
Expected
If the user likes the post in #post-detail-123, the #post-123’s toolbar should also reflect the updated state.
Actual Problem
In HTMX 2.0, hx-target=".post-toolbar-123" only updates the first matching element in the DOM, so only one of the toolbars is swapped instead of both.
Related
The multiswap extension doesn’t work because it’s designed for multiple IDs (e.g., #id, #id2), not classes.
Only elements with an id selector are supported, as the function internally uses OOB internal method. So it is not possible to use class or any other selectors.
Similiar disscussion in #44
If we use
hx-targetthis will catch just the first. What if ahx-targetsattribute where under the hood performs a querySelectAll?
Or a question on Stackoverflow: How to update 2 target with htmx?
Yeah htmx is currently only designed to have a single main target sorry. However you can wrap your update in a hx-swap-oob or maybe even use hx-select-oob as these allow multi target swaps.
<div hx-swap-oob="innerHTML:.post-detail-123>
<button hx-target=".post-toolbar-123">Unlike</button>
</div>