获取 iframe 中的元素
© 转载需要保留原始链接,未经明确许可,禁止商业使用。支持原创 CC BY-NC-SA 4.0
<iframe id="frame" src="" style="width: 500px;height: 500px;"></iframe>
场景描述
在页面中已显示的元素,通过 document.getElementById() document.querySelector() 等方法获取不到元素,审查元素之后才能获取到。
审查元素之后会发现不能获取的的元素位于 iframe 中。
获取 iframe 中的元素
// 方法一
document.querySelector('#frame').contentWindow.document.querySelector('.child');
document.querySelector('#frame').contentDocument.querySelector('.child');
// 方法二
window.frames['frame'].contentWindow.document.querySelector('.child');
window.frames['frame'].contentDocument.querySelector('.child');