Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First let's highlight the important parts:</p> <ol> <li>(first click) Takes the <code>source</code> element and put it inside the <code>target</code> element;</li> <li>(second click) Empties the <code>target</code> element and appends a new child (<code>p.dummy</code>) to it, effectively removing <code>source</code> from the DOM;</li> <li>Empties the <code>target</code> element and tries to re-append <code>source</code>, which is no longer present in the DOM.</li> </ol> <hr> <p>At first look, this wouldn't work in any browser as the <code>source</code> element has already been removed from the DOM. The "magic" here is JavaScript's <a href="https://stackoverflow.com/q/864516/1331430">Garbage Collector</a>. Browsers see that <code>sourceEl</code> is still scoped (inside the <code>setTimeout</code> closure) and do not trash the referenced DOM element inside of the <code>sourceEl</code> jQuery object.</p> <p><strong>The issue here is not JScript (Microsft's Javascript implementation)'s Garbage Collector, but rather how JScript handles the DOM parsing when setting an element's <code>innerHTML</code>.</strong></p> <p>Other browsers will simply detach all <code>childNode</code>s (whose will be collected by GC when there are no more active references) and parse the passed html string into DOM elements appending them to the DOM. Jscript, on the other hard, will also erase the detached <code>childNode</code>s' <code>innerHTML</code>/<code>childNode</code>s. Check this <a href="http://jsfiddle.net/zgKqV/1/" rel="nofollow noreferrer"><strong>fiddle</strong></a> for an illustration.</p> <p>The element, in fact, does still exist in IE and is appended to the DOM:</p> <p><img src="https://i.stack.imgur.com/MJ1BQ.png" alt="enter image description here"></p> <p>It just has no <code>childNode</code>s anymore.</p> <p>To prevent this kind of behavior, <a href="http://api.jquery.com/clone/" rel="nofollow noreferrer"><code>.clone()</code></a> the element (as mentioned in the question) or <a href="http://api.jquery.com/detach/" rel="nofollow noreferrer"><code>.detach()</code></a> it before calling <code>.html()</code> on its parent, if you intend to re-use the element instead of "overwriting" it.</p> <p>Here's a <a href="http://jsfiddle.net/2j3ZB/6/" rel="nofollow noreferrer"><strong>fiddle</strong></a> using <code>.detach()</code> before the element is overwritten, works fine in all browsers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload