跳到主要内容

获取 iframe 中的元素

长念
长念阅读约 1 分钟3 年前发布2 年前编辑
<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');