父页面parent.html
<body>
<div id="parent">parent</div>
<iframe id="ifr" src="child.html"></iframe>
</body>
子页面child.html
<body>
<div id="child">child</div>
</body>
//从parent页面获取child页面中id为child的元素
var ifr=document.getElementById('ifr');
ifr.onload=function(){
var child=ifr.contentWindow.document.getElementById('child');
console.log(child);//即为我们需要的元素
}
//从child页面获取parent页面id为parent的元素
var parent=window.parent.document.getElementById('parent');
或者window.top.document.getElementById('parent')都可以获取到
注意一点:获取child页面的元素一定要放在页面onload事件里面,否则页面没加载完成获取到的就是null