冰豆网

分享网络精彩
bingdou.com.cn

iFrame父子相互获取对方dom元素

时间:2023-08-31加入收藏

父页面 parent.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>父页面</title>
</head>
<body>
    <div class="parent">我是父页面的文字</div>
    <iframe src="./son.html"></iframe>
</body>
</html>


子页面 son.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>子页面</title>
</head>
<body>
    <div class="son">我是子页面的文字</div>
</body>
</html>


父页面获取子页面dom的方法

/* 必须用onload */
window.onload = () => {
    const sonWindow = document.querySelector("iframe").contentWindow;
    const sonDiv = sonWindow.document.querySelector(".son")
    console.log(sonDiv);
}


子页面获取父页面dom的方法

/* 必须用onload */
window.onload = () => {
    const parentWindow = window.parent;
    const parentDiv = parentWindow.document.querySelector(".parent")
    console.log(parentDiv);
}

打 赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

TGA: 技巧

分享到:


官方微信二维码冰豆网官方微信公众号