htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Method htmx.process doesn't work with already initialized elements

Open gbourant opened this issue 8 months ago • 5 comments

On the following conversation that I had with myself (so based), I found out that the method htmx.process doesn't not process already initialized elements.

I will demonstrate that use case below:

In the following example.html, everything will work as expected.

<form x-post="url" hx-trigger="input from:#otp">
      <input id="otp" type="text" />
</form>

But if we use document.querySelector('#otp').remove() to remove the input element, then the form becomes:

<form x-post="url" hx-trigger="input from:#otp">
</form>

So later, if we decide that we want to add again the input, the form becomes:

<form x-post="url" hx-trigger="input from:#otp">
      <input id="otp" type="text" />
</form>

The docs say: If javascript adds content to the DOM that has htmx attributes on it, you need to make sure that this content is initialized with the htmx.process() function.

As we can see, the new added input, does not have any htmx attribute but the form has hx-trigger="input from:#otp".

So if we try to htmx.process(document.querySelector('form')) it won't work.

Two things could happen, the htmx-internal-data.listenerInfos already contains an old reference to the old otp input, so it won't initialize it again or the form element already has initialized it's htmx-internal-data, so it will skip the initialization.

If I delete the htmx-internal-data and call the process function it will work.

Deleting htmx-internal-data is too hacky and I don't know the side effects of that.

Maybe we need to change how htmx.process works to be aware of such cases or add a second param htmx.process(element, force = true) which will take care of such cases.

gbourant avatar Mar 14 '25 04:03 gbourant