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

HaoOuBa
2021-05-26 / 2 评论 / 191 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年05月26日,已超过1157天没有更新,若内容或图片失效,请留言反馈。

父页面 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);
}
4

评论 (2)

取消
  1. 头像
    admin
    Windows 7 · Google Chrome

    戈夫岛

    回复
  2. 头像
    次次
    MacOS · Google Chrome

    太水了

    回复