林秀栋的技术博客

全局查找iframe元素及相反情况的方法

父页面找子页面中的元素

jQuery写法

$(window).load(function(){ //需等iframe加载完才能获取
    var a = $("#myIframe").contents().find("#b").text();
    console.log(a);
})

如果要取子iframe的子iframe中的元素,可以写:

$("#myIframe").contents().find("#myIframe2").contents().find("#c").text();

js写法

//父页面获取子页面元素
document.getElementById('myIframe').contentWindow.document.getElementById("b").innerText;
//父页面获取子页面的页面的元素
document.getElementById('myIframe').contentWindow.document.getElementById('myIframe2').contentWindow.document.getElementById("c").innerText;

子页面找父页面中的元素

jQuery写法

$(document).ready(function(){ //找父页面不需要等load完
    var b = $(window.parent.document).find("#a").text();
    console.log(b);
})

js写法

window.parent.document.getElementById("a").innerText;

子页面找祖父页面中的元素

jQuery写法

$(document).ready(function(){
    var c = $(window.top.document).find("#a").text();
    console.log(c);
})

$(window.parent.parent.document).find("#a").text(); //根据情况增减parent

js写法

window.top.document.getElementById("a").innerText;

window.parent.parent.document.getElementById("a").innerText;

小贴士

$(window.top.document.getElementById(“demo”))表示把id为demo的dom转为jq对象