现象:浏览器端通过开发者工具,无法通过document.getElementById()等方式获取到元素,但通过审查元素点击该元素后,再通过document.getElementById()等方式却能获取到元素。
原因:该元素在页面的iframe中,需要而当前Window的document只包含当前页面元素,不包含iframe中的元素,所以如果需要获取到iframe中的元素,需要首先获取到iframe中的document,然后通过该document 再获取对应元素。例如:document.getElementById("myIframe").contentWindow.document.getElementById("mySpan");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<span>页面span</span>
<iframe id="myIframe">
<span id="mySpan">iframe中的span</span>
</iframe>
</body>
</html>