获取 iframe 里面的节点

获取 iframe 里面的节点

注意点:
1.一定要是同源
2.需要等iframe加载完了再去获取,否则就是空

//html
 <iframe
      src="http://localhost:3000/index2.html"
      name="iframe"
      id="iframe"
    ></iframe>

//script
  //window.frames[0] 另一种获取iframe的方法
      let iframe = document.getElementById("iframe");
      let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
      console.log(innerDoc.getElementsByTagName("div"), "iframe未知");
      document.getElementById("iframe").onload = function () {
        let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
        console.log(innerDoc.getElementsByTagName("div"), "iframe加载完了");
      };

结果如下

原文地址:https://www.cnblogs.com/heihei-haha/p/14748074.html