Firefox中的`ImportNode`并从`iframe`中提取元素 [英] `ImportNode` in Firefox and extracting an element from an `iframe`
问题描述
我正在尝试使用以下示例理解html中的 importNode
。
I am trying to understand importNode
in html using the following example.
假设我们有一个 content.html
:
<html>
<body>
<nav id="sidebar1" class="sidebar">
Hi there!
</nav>
</body>
</html>
和 main.html
:
<html>
<body>
<iframe src='content.html' hidden='true'></iframe>
<script>
var idframe = document.getElementsByTagName("iframe")[0];
var oldNode = idframe.contentWindow.document.getElementsByTagName("nav")[0];
var newNode = document.importNode(oldNode, true);
document.getElementsByTagName("body")[0].appendChild(newNode);
alert("HI!!!");
</script>
</body>
</html>
我收到错误:
TypeError: Argument 1 of Document.importNode is not an object.
var newNode = document.importNode(oldNode, true);
从iframe获取元素并将其插入到我的html中的正确方法是什么?
What is the proper way to get an element form an iframe and insert it into my html?
推荐答案
您只能在加载iframe文档后访问iframe文档的内容。这可以通过不同的方式实现:
You can only access content of the iframe document after the iframe document has been loaded. This can be accomplished different ways:
- 将访问代码放入
load
main的处理程序(包含iframe
元素)文档窗口, - 或在
DOMContentLoaded $内c $ c>在
iframe
中加载的文件的事件监听器。
- either by putting your accessing code into
load
handler of the main (that containsiframe
element) document window, - or inside a
DOMContentLoaded
event listener of the document loaded iniframe
.
以下是使用加载
主文档的窗口
事件的示例:
Below is example of using load
event of window
of the main document:
window.addEventListener('load', function() {
var iframe = document.getElementsByTagName("iframe")[0];
var oldNode = iframe.contentWindow.document.getElementById("myNode");
var newNode = document.importNode(oldNode, true);
document.body.insertBefore(newNode, document.body.firstChild);
}, false);
否则,当您尝试访问iframe内容时,iframe内容尚未加载。
Otherwise, iframe content is not yet loaded when you try to access it.
请参阅JSFiddle上的实例(iframe内容编码在 srcdoc
iframe
的属性,因为我不知道能否在JSFiddle创建子文档而不创建单独的小提琴。
See the live example at JSFiddle (iframe content is placed encoded in the srcdoc
attribute of the iframe
just because I'm not aware of ability to create subdocuments at JSFiddle without creating a separate fiddle).
这篇关于Firefox中的`ImportNode`并从`iframe`中提取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!