views:

166

answers:

1

Hi all,

Whats the wayto modify the "body" of a dom tree like this using javascript:

Original htm:    <html> <head></head>   <body>  blah blah blah  </body>  </html>

Modified html:    <html>  <head> </head>  <abc> <body> blah blah blad </body> </abc> </html>

That is, I wish to put the whole body node inside another node.

The code I am trying is:

// Create an iframe

var orig_iframe = document.createElement('iframe');

// Copy body's content inside iframe (hopefully!)

orig_iframe.contentDocument.innerHTML= document.body.innerHTML;

// Set document body to null

document.body.innerHTML = '';

// Add iframe to body

document.body.appendChild(orig_iframe);

which doesnt work. Obviously I am missing something!

Thanks!

+1  A: 

orig_iframe.contentDocument.innerHTML= document.body.innerHTML;

There's no innerHTML property on HTMLDocument, only on HTMLElement. You'd probably want to set innerHTML on the iframe document's body element.

However, writing iframe​s dynamically has some browser wrinkles.

var html= document.body.innerHTML;
var iframe= document.createElement('iframe');
document.body.appendChild(iframe);
var idoc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
idoc.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;');
idoc.close();
idoc.body.innerHTML= html;

The business with contentWindow is necessary for IE up to version 7, which do not support the standard property contentDocument.

The write() call is to ensure that a minimal document is present in the iframe so that you can then set innerHTML on its body. The <!DOCTYPE declaration in it is required to put that window into Standards Mode (which is hopefully what you're using on the main document too).

Whilst you could document.write the HTML content to the new document, that would cause any <script> elements inside the body to execute again in the new document, which you probably don't want. Writing to innerHTML avoids immediate execution of any scripts in the string.

bobince