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 (tables, select boxes, inputs, etc.).
The elements have event listeners on them, so I need to preserve them after swapping the main divs.
I have access to jQuery 1.5. So answers with it are OK.
To swap two divs without losing event handlers or breaking DOM references, you can just move them in the DOM. The key is NOT to change the innerHTML because that recreates new DOM nodes from scratch and all prior event handlers on those DOM objects are lost.
But, if you just move the DOM elements to a new place in the DOM, all events stay attached because the DOM elements are only reparented without changing the DOM elements themselves.
Here’s a quick function that would swap two elements in the DOM. It should work with any two elements as long as one is not a child of the other:
You can see it work here: http://jsfiddle.net/jfriend00/NThjN/
And here’s a version that works without the temporary element inserted:
Working demo: http://jsfiddle.net/jfriend00/oq92jqrb/