Swap two html elements and preserve event listeners on them

前端 未结 8 1628
醉酒成梦
醉酒成梦 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条回答
  •  粉色の甜心
    2020-12-05 18:11

    If you keep track of the two elements' parentNodes and the nextSibling of one, you can swap two elements with their children without any temporary placeholders.

    If the second element is an only child, or the last child of its parent, its replacement is (properly) appended to the parent.

    function swap(a, b){
        var p1= a.parentNode, p2= b.parentNode, sib= b.nextSibling;
        if(sib=== a) sib= sib.nextSibling;
        p1.replaceChild(b, a);
        if(sib) p2.insertBefore(a, sib);
        else p2.appendChild(a);
        return true;
    }
    

提交回复
热议问题