htmx
htmx copied to clipboard
[feat] Preserve attributes while swaping with `outerHTML`.
Hi :smile:
I really like the project, but I'm still new and don't know all the tricks.. I'm using htmx with alpine.js and I'm very happy with the simplicity these two projects bring with them.
I'm working on a project where I ran into a problem when I want to swap an element with hx-swap="outerHTML" , sometimes I would like some attributes of the element to be transferred to the new element..
I couldn't find anywhere in the documentation how to do this so I created an simple extension that does just that: htmx-preserve-attr
The basic idea:
<!-- index.html -->
<body hx-ext="preserve-attr">
<div hx:foo="bar" hx-get="/new-element" hx-swap="outerHTML" hx-trigger="load">old element</div>
</body>
<!-- new-element.html -->
<div class="something">new element</div>
Output:
<div foo="bar" class="something">new element</div>
It would be nice if you would perhaps consider the full implementation of this..
Hey, cool extension. :)
Given you are using innerHTML instead, your new content could have an "hx-on load" trigger to remove unwanted attributes or set new ones, or am I misunderstanding?
For me I prefer an outer swap to really be an outer swap. :)
Wouldn’t it be better to keep it as extension for those who need this?
@andryyy Yes, you're right, I didn't know that this could be done via hx-on:load. But I didn't like innerHTML swap because it creates a new element inside an old one and that bothered me..
What i'm trying to do is something like calling a custom alpinejs component like this:
<!-- index.html -->
<loader hx:x-data={ time: 1000 }" hx-get="/loader" hx-target="this" hx-swap="outerHTML" hx-trigger="load"></loader>
and then i create whole component in one file loader.html that can access time although it is not defined in that file
<!-- loader.html -->
<loader x-init="delay(time)"></loader>
so I get an output like this that works
<!-- index.html -->
<loader x-data="{ time: 1000 }" x-init="delay(time)></loader>
it looks like calling a function with parameters, but it's actually a component..
But I agree with you that this should remain as an extension because I think this is an "edge case" and i just like using it like this.. :upside_down_face: