2

I want to append an object, that was created in a parent window to a child window:

div = document.createElement( "div" );
document.body.appendChild( div );
// Here come div's atts;
render = window.open().document;
render.body.appendChild( div );

but the new DIV is appended only to the child window. If I comment the last line - the div is appended to the parent window. Can that be solved?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Michael Sazonov
  • 1,531
  • 11
  • 21

2 Answers2

3

Editing since I misread the question:

newelement = element.cloneNode(true); // true to clone children too

Still there is no html or body in the new window that it can be appended to. At least not in chrome.

Try this instead:

<html>
<body>
    <script>
        div = document.createElement( "div" );
        // add some text to know if it's really there
        div.innerText = 'text of the div';
        document.body.appendChild( div );
        // Here come div's atts;
        render = window.open().document;
        // create the body of the new document
        render.write('<html><body></body></html>');
        // now you can append the div
        render.body.appendChild( div );
        alert(render.body.innerHTML);
    </script>
</body>
</html>
Asken
  • 7,679
  • 10
  • 45
  • 77
  • Please, read carefully... The div is appended first to the parent window, but then immediately appended to the child window. You even can see the "jump" – Michael Sazonov Dec 02 '11 at 13:25
  • 1
    Yeah, I see... you need to clone it... same as always with javascript. You're changing the object. – Asken Dec 02 '11 at 13:36
1

Have you tried creating a copy of that div and then appending that to the child instead of the original div?

Edit: Okay, then yeah, that would be the cloneNode function.

clone = div.cloneNode(true);
render = window.open().document;
render.body.appendChild(clone);
U-DON
  • 2,102
  • 14
  • 14
  • That's what I was looking for. Is there a function (Not jQuery) to clone elements? The problem is that I need exactly the same node tree in both windows. – Michael Sazonov Dec 02 '11 at 13:28