htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Should cloneAttributes check if settling attributes exists?

Open morindo opened this issue 2 years ago • 0 comments

I have case when an old input with a class attribute (ex. class="bg-red") is swapped with a new input (with no class attribute), the class attribute is merged with the old one, keeping the bg-red class. Notice that if I set an empty class attribute class="" on the new input, the merge result is as expected.

Ex.:

Old input (mergeFrom): <input id="id1" type="text" value="123" class="bg-red" />

New input from HTMX response (mergeTo): <input id="id1" type="text" value="123" />

Result: <input id="id1" type="text" value="123" class="bg-red" />

Expected result: <input id="id1" type="text" value="123" />

Propose solution would be:

function cloneAttributes(mergeTo, mergeFrom) {
    forEach(mergeTo.attributes, function (attr) {
        if (!mergeFrom.hasAttribute(attr.name) && shouldSettleAttribute(attr.name)) {
            mergeTo.removeAttribute(attr.name)
        }
    });
    forEach(mergeFrom.attributes, function (attr) {
        //if (shouldSettleAttribute(attr.name)) { // Old code.
        if (mergeTo.hasAttribute(attr.name) && shouldSettleAttribute(attr.name)) { // New code
            mergeTo.setAttribute(attr.name, attr.value);
        }
    });
}

Does this make sense?

morindo avatar Dec 05 '23 03:12 morindo