Javascript 如何使用 document.getElementById 在 iframe 中选取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14451358/
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 pick element inside iframe using document.getElementById
提问by ishk
I have a iframelike this
我有一个iframe这样的
<iframe name="myframe1" id="myframe1" width="100%" height="100%" src="a.html">
<html>
<head></head>
<frameset name="myframe2" cols="0%, 100%" border="0" frameBorder="0" frameSpacing="0">
<frame name="page1" src="c.html" scrolling="no"></frame>
<frame name="page2" src="d.html" >
<html>
<head></head>
<body id="top">
<div id="div1">
<div id="div2">
<div id="div3">
<ul id="x">
<li>a</li>
<li>b</li>
</ul>
</div>
</div>
</div>
</body>
</html>
</frame>
</frameset>
</html>
</iframe>
I want to refer to the element "x". I tried in several ways but I couldn't find a solution.
我想引用元素“x”。我尝试了多种方法,但找不到解决方案。
回答by Fabrício Matté
document.getElementById('myframe1').contentWindow.document.getElementById('x')
contentWindowis supported by all browsers including the older versions of IE.
contentWindow所有浏览器都支持,包括旧版本的 IE。
Note that if the iframe's srcis from another domain, you won't be able to access its content due to the Same Origin Policy.
请注意,如果iframe'ssrc来自另一个域,由于同源策略,您将无法访问其内容。
回答by mbharanidharan88
use contentDocumentto achieve this
用于contentDocument实现此目的
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
var ulObj = innerDoc.getElementById("ID_TO_SEARCH");
回答by Pat
(this is to add to the chosen answer)
(这是添加到所选答案中)
Make sure the iframeis loaded before you
确保iframe在你之前加载
contentWindow.document
Otherwise, your getElementByIdwill be null.
否则,你getElementById会的null。
PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframeload before selecting the inner-iframe element.
PS:无法评论,评论的声誉仍然很低,但这是对所选答案的跟进,因为我花了一些很好的调试时间试图弄清楚我应该iframe在选择内部 iframe 元素之前强制加载。
回答by Divyanshu Rawat
In my case I was trying to grab pdfTrontoolbar, but unfortunately its IDchanges every-time you refresh the page.
就我而言,我试图获取pdfTron工具栏,但不幸的是,每次刷新页面时它的ID 都会更改。
So, I ended up grabbing it by doing so.
所以,我最终通过这样做抓住了它。
const pdfToolbar = document.getElementsByTagName('iframe')[0].contentWindow.document.getElementById('HeaderItems');
As in the array written by tagName you will always have the fixed index for iFrames in your application.
正如在 tagName 写入的数组中一样,您的应用程序中将始终拥有 iFrame 的固定索引。

