父子页面(iframe)相互获取对方dom元素

现在iframe的使用虽然开始越来越少,但是还是有牵涉到iframe的使用情况,特别是多个iframe互相嵌套,又要进行获取的情况。

现在整理了父子iframe之间互相获取的方式。

(1)父页面获取子页面的方式。

主要通过:

iframe的contentWindow属性,代表iframe所在的window对象。

示例如下:

<script type="text/javascript">  
    window.onload = function(){  
        var cWindow = document.getElementById('iframeId').contentWindow;  
        var div=cWindow .document.getElementById('divId');  
       //some other operation
    }  
      
    </script> 

....

<iframe id="iframeId" src="iframe.html" width="100" height="100">
<div id="divId"></div>
</iframe>

(2) 通过子元素获取父元素

主要通过 window.parent 进行获取

示例代码如下:

<div id-"pDivId"></div>
<iframe src="iframe.html" width="100" height="100">

</iframe>

iframe.html页面中的内容为(实现对父元素的操作):

 <script type="text/javascript">  
    window.onload = function(){  
        var pWindow= window.parent;  
        var pDiv=pWindow.document.getElementById('pDivId');  
       //some other operation
    }  
    </script>  
原文地址:https://www.cnblogs.com/asdfq/p/6009798.html