Swap two html elements and preserve event listeners on them

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

    This is a simpler function for swapping two elements without actually reloading the element...

    function swapElements(obj1, obj2) {
        obj2.nextSibling === obj1
        ? obj1.parentNode.insertBefore(obj2, obj1.nextSibling)
        : obj1.parentNode.insertBefore(obj2, obj1); 
    }
    

    Note: if the obj1 has an embedded video like YouTube, it will not reload when swapped. It's just the position of the elements that changed.

提交回复
热议问题