Swap two html elements and preserve event listeners on them

前端 未结 8 1645
醉酒成梦
醉酒成梦 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:05

    My simple function seems to be the shortest and most widely compatible. It doesn't need placeholders or reload elements or anything messy like that:

    function swapElements(el1, el2) {
        var p2 = el2.parentNode, n2 = el2.nextSibling
        if (n2 === el1) return p2.insertBefore(el1, el2)
        el1.parentNode.insertBefore(el2, el1);
        p2.insertBefore(el1, n2);
    }
    

提交回复
热议问题