How to move an iFrame in the DOM without losing its state?

Tags: , , ,

Take a look at this simple HTML:

<div id="wrap1">
  <iframe id="iframe1"></iframe>
<div id="warp2">
  <iframe id="iframe2"></iframe>

Let’s say I wanted to move the wraps so that the #wrap2 would be before the #wrap1. The iframes are polluted by JavaScript. I am aware of jQuery’s .insertAfter() and .insertBefore(). However, when I use those, the iFrame loses all of its HTML, and JavaScript variables and events.

Lets say the following was the iFrame’s HTML:

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      // The variable below would change on click
      // This represents changes on variables after the code is loaded
      // These changes should remain after the iFrame is moved
      variableThatChanges = false;
          variableThatChanges = true; 
    <div id='anything'>Illustrative Example</div>

In the above code, the variable variableThatChanges would…change if the user clicked on the body. This variable, and the click event, should remain after the iFrame is moved (along with any other variables/events that have been started)

My question is the following: with JavaScript (with or without jQuery), how can I move the wrap nodes in the DOM (and their iframe childs) so that the iFrame’s window stays the same, and the iFrame’s events/variables/etc stay the same?


It isn’t possible to move an iframe from one place in the dom to another without it reloading.

Here is an example to show that even using native JavaScript the iFrames still reload:

var wrap1 = document.getElementById('wrap1');
var wrap2 = document.getElementById('wrap2');

Source: stackoverflow