如何在嵌套iframe中查找特定元素

时间:2019-01-04 10:40:39

标签: javascript html css

我需要从父组件中找到一个位于iframe内的特定元素,其结构应如下所示:(仅作为示例)
编辑: 请参阅以下有关此示例性质的注释

<iframe id ='if1'>
    <iframe id ='if2'>
        <iframe id ='if3'>
            <iframe id ='if4'>
                <input type='hidden' id ='elementToBeFound'>
            </iframe>
        </iframe>
    </iframe>
</iframe>

现在,我该如何使用JavaScript? (也可以是jquery或其他助手)
我有第一个iframe('if1')的引用,我想搜索所有子节点,直到找到'elementToBeFound'。
有可能吗?
提前致谢。

我的问题与现有问题不同,因为我想访问iframe中的多个iframe,而不仅仅是一个级别。

3 个答案:

答案 0 :(得分:1)

我相信这样的事情应该起作用:

const elem = document.getElementById('if1').contentDocument
.getElementById('if2').contentDocument
.getElementById('if3').contentDocument
.getElementById('if4').contentDocument
.getElementById('elementToBeFound')

但是请确保所有窗口都应加载以执行此操作。在实际的工作环境中,您可能需要侦听每个iframe的load事件才能检查其中的内容。

答案 1 :(得分:0)

您可以使用此函数查询页面上的任何元素,而不管它是否嵌套在iframe中:

function querySelectorAllInIframes(selector) {
  let elements = [];

  const recurse = (contentWindow = window) => {

    const iframes = contentWindow.document.body.querySelectorAll('iframe');
    iframes.forEach(iframe => recurse(iframe.contentWindow));
    
    elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
  }

  recurse();

  return elements;
};

querySelectorAllInIframes('#elementToBeFound');

注意:请记住,页面上的每个iframe都必须具有相同的来源,否则此函数将引发错误。

答案 2 :(得分:-1)

您可以使用iframe.contentWindow调用来获取div元素。

这里是示例:

  

注意:您必须使用“ src”(外部iframe)使其正常工作

   <!DOCTYPE html>
    <html>
    <head>
      <title>IF1</title>
    </head>

    <body>
      <iframe id='if1' src="./iframe2.html">
        <!-- <iframe id='if2'>
          <iframe id='if3'>
            <iframe id='if4'> -->
              <!-- <div id='elementToFind'>Hello</div> -->
            <!-- </iframe>
          </iframe>
        </iframe> -->
      </iframe>

      <script>

        window.onload = function() {
          let if1 = document.getElementById('if1').contentWindow;
          let if2 = if1.document.getElementById('if2').contentWindow;
          let div = if2.document.getElementById('elementToFind');
          console.log(div)
        }

      </script>
    </body>

    </html>
相关问题