bigskysoftware / bigskysoftware/htmx

Weird behaviour when swapping innerHTML vs outerHTML

Open
#2,499 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
JavaScript
Stars
49.4k
Forks
1.7k
Avg merge
3d 22h
Merged PRs (30d)
30

Description

Hello, I have this weird case. I use `HTMX` together with `TomSelect`.
I init my selects after swapping like so:

document.body.addEventListener('htmx:afterSettle', async (event) => {
event.detail.target.querySelectorAll("[is-tomselect]").forEach((elem) => {
new TomSelect(elem, {...});
});
});

The returned html looked like so:


{% partial %}
...
....

{% endpartial %}

First swap eveything worked well, but if I did the swap a second time I would get this error:
```Error: Tom Select already initialized on this element```
Which is weird because the select was supposed to be replaced with a new fresh one.

The error is thrown by tomselect with this line of code of the constructor:
```if (input.tomselect) {
throw new Error('Tom Select already initialized on this element');
}```
It checks to see if the elements has already been initialized. But all of this takes place after the dom has settled so all elements should be "fresh".

After a lot of debugging I found out that if I change the returned html to one below everything worked no matter how many swaps I did:
```


{% partial %}
...
....

{% endpartial %}

```

Somehow changing the swap method to `innerHTML` instead `outerHTML` deletes the old `tomselect` instances and everything works. But using `outerHTML` keeps the instances alive.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.