问题描述
无法操作iframe内的元素
问题出现的环境背景及自己尝试过哪些方法
本地有两个文件:index.html
,iframe1.html
。本地运行index.html
后通过iframe标签
获取iframe1
内部的元素。却无法获取。
相关代码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe src="iframe1.html" name="iframe1" id="iframe1"></iframe>
<script type="text/javascript">
console.log(document.getElementById('iframe1').contentDocument.getElementById('title'));
</script>
</body>
</html>
iframe1.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p id="title">frame1</p>
</body>
</html>
你期待的结果是什么?实际看到的错误信息又是什么?
在本地运行 index.html
,我无法得到iframe1
中的p
标签。
<iframe src="iframe1.html" name="iframe1" id="iframe1"></iframe>
是相对路径,怎么会跨域呢?需要等iframe加载完了。不然iframe都是空白的,怎么会获取到?
评论不能贴图。这里标识的是作用域,这里写的和你的页面是同一个作用域吗?