htmx icon indicating copy to clipboard operation
htmx copied to clipboard

HX-Trigger response header target only targets first item

Open flew2bits opened this issue 4 months ago • 2 comments

I'm trying to trigger the same named event on multiple targets from an HX-Trigger response header. I'm sending back something like the following:

HX-Trigger: {"refresh": {"target": "#target-1,#target-2"}}

I've also tried the following variations:

HX-Trigger: {"refresh": [{"target": "#target-1"},{"target": "#target-2"}]} HX-Trigger: {"refresh": {"target": ".target-shared-class"}}

What I ultimately found is that once htmx determines the target, either as the triggering element or the element named in target, the code that resolves that target DOM element calls .querySelector, which is why it only gets the first item in the list.

Is there any reason this couldn't be modified to be .querySelectorAll and use .forEach to process the event on all of the returned results?

My workaround at this point is I have another event handler that takes a targets selector and an event name and calls the trigger functionality on each of them, but it seems like this should work out-of-the-box.

flew2bits avatar Aug 29 '25 13:08 flew2bits

If anyone is trying to implement similar functionality, here's how I did it:

document.addEventListener('multi-trigger', evt => {
    const targets = evt.detail.targets;
    const event = evt.detail.event;
    if (!targets || !event) return;
    document.querySelectorAll(targets).forEach(elt => htmx.trigger(elt, event));
})

Then, include a response header HX-Trigger: {"multi-trigger": {"targets": ".my-targets", "event": "my-event"}}

flew2bits avatar Aug 29 '25 13:08 flew2bits

yes the hx-trigger is designed to only trigger the event to a single element because this is how the internal trigger event function is designed to work. But as you have found it should be easy to work around this limitation if required. If it is htmx actions you are triggering you can also use the the from: modifier on the hx-trigger attribute to allow multiple elements to trigger from a named event on a shared element or the body. If all elements listen on body for example then because of event bubbling they will all be triggered at once which may simplify your design.

MichaelWest22 avatar Sep 02 '25 12:09 MichaelWest22