Swap two html elements and preserve event listeners on them

前端 未结 8 1646
醉酒成梦
醉酒成梦 2020-12-05 17:55

There are similar questions, but all the answers are for swapping html elements only for the content inside.

I need to swap two divs, with lots of content in them (t

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 18:08

    This all is very strange considering the fact that o1.swapNode(o2); works very well in IE for very long time. In my case of object and text nodes intermixed, works only one version (already shown here):

    let t = document.createElement("div");
    o1.parentNode.insertBefore(t, o1);
    o2.parentNode.insertBefore(o1, o2);
    t.parentNode.insertBefore(o2, t);
    t.parentNode.removeChild(t);
    

    Yes, I hate creating temporary node, but the above version without this trick fails if you use it straight (without calling function). Sometimes you don't want to call a function.

提交回复
热议问题