开发者

Javascript dom tree modification

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

Original htm:    <html> <h开发者_JAVA百科ead></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!


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"><html><head></head><body></body></html>');
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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜