Accessing an imported element after the original DOMDocument is destroyed <p>I've been messing around with DOMDocument lately, and I've noticed that in order to transfer elements from one document to the next, I have to call <a href="http://php.net/manual/en/domdocument.importnode.php" rel="nofollow"><code>$DOMDocument-&gt;importNode()</code></a> on the target <code>DOMDocument</code>.</p> <p>However, I'm running into weird issues, where once the originating document is destroyed, the cloned element misbehaves.</p> <hr> <p>For example, here's some lovely working code:</p> <pre class="lang-php prettyprint-override"><code>$dom1 = new DOMDocument; $dom2 = new DOMDocument; $dom2-&gt;loadHTML('&lt;div id="div"&gt;&lt;span class="inner"&gt;&lt;/span&gt;&lt;/div&gt;'); $div = $dom2-&gt;getElementById('div'); $children = $dom1-&gt;importNode( $div, true )-&gt;childNodes; echo $children-&gt;item(0)-&gt;tagName; // Output: "span" </code></pre> <p>Here's a demo: <a href="http://codepad.viper-7.com/pjd9Ty" rel="nofollow">http://codepad.viper-7.com/pjd9Ty</a></p> <hr> <p>The problem arises when I try using the elements after their original document is out of scope:</p> <pre class="lang-php prettyprint-override"><code>global $dom; $dom = new DOMDocument; function get_div_children () { global $dom; $local_dom = new DOMDocument; $local_dom-&gt;loadHTML('&lt;div id="div"&gt;&lt;span class="inner"&gt;&lt;/span&gt;&lt;/div&gt;'); $div = $local_dom-&gt;getElementById('div'); return $dom-&gt;importNode( $div, true )-&gt;childNodes; } echo get_div_children()-&gt;item(0)-&gt;tagName; </code></pre> <p>The above results in the following errors:</p> <blockquote> <p><strong>PHP Warning</strong>: Couldn't fetch <code>DOMElement</code>. Node no longer exists in ...<br> <strong>PHP Notice</strong>: Undefined property: <code>DOMElement::$tagName</code> in ...</p> </blockquote> <p>Here's a demo: <a href="http://codepad.viper-7.com/c0kqOA" rel="nofollow">http://codepad.viper-7.com/c0kqOA</a></p> <hr> <p>My question is twofold:</p> <ol> <li><p>Shouldn't the returned elements exist even after the original document was destroyed, since they were cloned into the current document?</p></li> <li><p>A workaround. For various reasons, I have to manipulate the elements after the original document is destroyed, but before I actually insert them into the DOM of the other <code>DOMDocument</code>. Is there any way to accomplish this?</p></li> </ol> <hr> <p><strong>Clarification:</strong> I understand that if the elements are inserted into the DOM, it behaves as expected. But, as outlined above, my setup calls for the elements to be manipulated before being inserted into the DOM (long story). Given that the first example here works - and that manipulating elements outside of the DOM is standard procedure in JavaScript - shouldn't this be possible here as well?</p>