Javascript dom树修改
使用javascript修改dom树的“body”的方法是什么:
Original htm: <html> <head></head> <body> blah blah blah </body> </html>
Modified html: <html> <head> </head> <abc> <body> blah blah blad </body> </abc> </html>
也就是说,我希望将整个body节点放入另一个节点中。
我正在尝试的代码是:
// Create an iframe
var orig_iframe = document.createElement('iframe');
// 在 iframe 中复制正文内容(希望如此!)
orig_iframe.contentDocument.innerHTML= document.body.innerHTML;
// 将文档正文设置为 null
document.body.innerHTML = '';
// 将 iframe 添加到 body
document.body.appendChild(orig_iframe);
这是行不通的。显然我错过了一些东西!
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HTMLDocument
上没有innerHTML
属性,只有HTMLElement
上有。您可能希望在 iframe 文档的body
元素上设置innerHTML
。然而,动态编写
iframe
会导致浏览器出现一些问题。contentWindow
的业务对于 IE 版本 7 之前是必需的,该版本不支持标准属性contentDocument
。write()
调用是为了确保iframe
中存在最小文档,以便您可以在其主体上设置innerHTML
。其中的声明需要将该窗口置于标准模式(希望这也是您在主文档上使用的模式)。
虽然您可以将
document.write
HTML 内容写入新文档,但这会导致正文中的任何元素再次执行在新文档中,您可能不想要这样。写入
innerHTML
可以避免立即执行字符串中的任何脚本。There's no
innerHTML
property onHTMLDocument
, only onHTMLElement
. You'd probably want to setinnerHTML
on the iframe document'sbody
element.However, writing
iframe
s dynamically has some browser wrinkles.The business with
contentWindow
is necessary for IE up to version 7, which do not support the standard propertycontentDocument
.The
write()
call is to ensure that a minimal document is present in theiframe
so that you can then setinnerHTML
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 toinnerHTML
avoids immediate execution of any scripts in the string.