使用contentDocument属性来访问iframe中的文档对象
链接文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#app {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<body>
<div id="app"></div>
</body>
</html>
获取iframe嵌套文件中的元素
<iframe src="./index2.html" id="iframe" frameborder="0"></iframe>
<button id="btn">获取div元素</button>
<script>
const btn = document.getElementById('btn')
const iframe = document.getElementById("iframe")
btn.onclick = () => {
// 通过contentDocument对象或者contentWindow
const myIframe = iframe.contentDocument || iframe.contentWindow.document;
console.log(myIframe)
console.log(myIframe.getElementById('app'))
}
</script>
请注意,由于跨域问题,您可能无法访问来自不同域的iframe中的文档。在这种情况下,您需要使用其他技术来解决此问题,例如跨域消息传递或JSONP