javascript 如何在 iframe 中选择一个 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9337557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select a div within an iframe?
提问by amillet89
I'm trying to take the contents of a div within an iframe, delete the iframe, and display only the div. I can't figure out why this won't work- I am not sure of whether to use contentWindow or contentDocument.. Any pointers? Thanks!
我试图在 iframe 中获取 div 的内容,删除 iframe,并仅显示 div。我不知道为什么这不起作用 - 我不确定是使用 contentWindow 还是 contentDocument .. 有什么指示吗?谢谢!
I have one div with id "iframe", within that the iframe with id "embedded_article",
我有一个 ID 为“iframe”的 div,在那个 ID 为“embedded_article”的 iframe 中,
<script type="text/javascript">
function getContentFromIframe()
{
var parent = document.getElementById('iframe');
var child = document.getElementById('embedded_article');
var oldContent = child.contentWindow.document.innerHTML;
var newContent = child.contentWindow.document.getElementById('ec-article').innerHTML;
document.getElementById('iframe').removeChild(document.getElementById('embedded_article'));
parent.innerHTML = newContent;
}
</script>
采纳答案by Dagg Nabbit
Your example:
你的例子:
document.getElementById('iframe').removeChild(document.getElementById('embedded_article'));
Should look something like:
应该看起来像:
var element = frames['iframe'].document.getElementById('embedded_article');
element.parentNode.removeChild(element);
window.frames['yourFrameId']
evaluates to the window
object associated with your frame. when you use document.getElementById
, you want to use the document
belonging to your frame's window
, not the document
in your main window. The rest should be self-explanitory.
window.frames['yourFrameId']
评估为window
与您的框架关联的对象。当您使用 时document.getElementById
,您希望使用document
属于您框架的window
,而不是document
主窗口中的 。其余的应该是不言自明的。
回答by Jaspreet Chahal
to get to the div inside an iFrame you can try something like this
要进入 iFrame 内的 div,您可以尝试这样的操作
var div = document.getElementById("YourIFrameID").contentWindow.document.body.getElementById("YOUR_DIV_ID")