How to update 2 target with htmx?
Asked Answered
D

2

5

I have following htmx code

<button
        hx-get="/views/users/byId/someId"
        hx-target=".details">Details</button>
<div class="details">first</div>
<div class="details">second</div>

This only change first div and second div does not change I want to update both div in the bottom with same class name How to do this this?

I also tried multiple div but as we cant have multiple div that was giving error

Departmentalism answered 11/6, 2023 at 17:41 Comment(0)
C
8

The documentation for hx-target says that transactions like hx-get and hx-post will only replace the first DOM node on the page that matches the criteria. This is true whether you're using the default action (which swaps out the current DOM node) or specifying your own CSS selector.

This is a pretty common question for htmx, and there's an example of several different ways to accomplish this on the website. This example lists three possible solutions:

  1. Use hx-target to swap a larger portion of the page.
  2. Use Out of Band Swaps
  3. Use custom events and hx-trigger to trigger additional swaps that follow after the initial one.

It's hard to say what's the "right" answer without looking at the rest of your use case. But my guess is that you could just expand the area you're targeting and call it a day.

<div id="swap-all-this">
    <button
        hx-get="/views/users/byId/someId"
        hx-target="#swap-all-this">Details</button>
    <div class="details">first</div>
    <div class="details">second</div>
</div>

Cairn answered 11/6, 2023 at 19:56 Comment(0)
D
0

Note there is also the multiswap extension, which can target multiple elements.

Eg

<button
  hx-get="/views/users/byId/someId"
  hx-target=".details"
  hx-swap="multi:#id1,#id" <!--THIS IS NEW HERE-->
  >Details</button>
<div class="details" id="id1">first</div>
<div class="details" id="id2">second</div>

Note that you would have to include and enable the htmx extension according to the documentation.

Dermatosis answered 2/2 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.