【问题标题】:How to pick element inside iframe using document.getElementById如何使用 document.getElementById 在 iframe 中选择元素
【发布时间】:2013-01-05 06:12:14
【问题描述】:

我有一个这样的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>

我想引用元素“x”。我尝试了几种方法,但找不到解决方案。

【问题讨论】:

标签: javascript html iframe getelementbyid frameset


【解决方案1】:
document.getElementById('myframe1').contentWindow.document.getElementById('x')

Fiddle

所有浏览器都支持contentWindow,包括旧版IE。

请注意,如果iframesrc 来自另一个域,由于Same Origin Policy,您将无法访问其内容。

【讨论】:

  • 最后一句很重要;) 你框架的来源必须在你页面的同一个域中
  • 但是如果框架的源不属于同一个域怎么办?如何解决?问候,米克。
【解决方案2】:

使用contentDocument 来实现这一点

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) 
               ? iframe.contentDocument 
               : iframe.contentWindow.document;

var ulObj = innerDoc.getElementById("ID_TO_SEARCH");

【讨论】:

    【解决方案3】:

    (这是添加到所选答案中)

    确保iframe在你之前加载

    contentWindow.document
    

    否则,您的getElementById 将是null

    PS:无法发表评论,评论的声誉仍然很低,但这是对所选答案的后续跟进,因为我花了一些很好的调试时间试图弄清楚我应该在选择之前强制 iframe 加载内部 iframe 元素。

    【讨论】:

      【解决方案4】:

      您需要确保框架已完全加载 最好的方法是使用 onload:

      <iframe id="nesgt" src="" onload="custom()"></iframe>
      
      function custom(){
          document.getElementById("nesgt").contentWindow.document;
          }
      

      这个函数会在 iframe 完全加载后自动运行。

      【讨论】:

        【解决方案5】:

        在我的例子中,我试图抓取 pdfTron 工具栏,但不幸的是,每次刷新页面时它的 ID 都会发生变化。

        所以,我最终通过这样做抓住了它。

        const pdfToolbar = document.getElementsByTagName('iframe')[0].contentWindow.document.getElementById('HeaderItems');
        

        就像在 tagName 写入的数组中一样,您的应用程序中的 iFrame 将始终具有固定索引。

        【讨论】:

          猜你喜欢
          • 2015-05-03
          • 1970-01-01
          • 1970-01-01
          • 2011-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多