我面臨無法遍歷 iframe 內的 dom 的情況。我的代碼如下。當我嘗試訪問標簽childNodes時,控制臺將顯示正文標簽內body沒有。childNodes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<iframe id="container"
src="./resources/c07.xhtml"
frameborder="0"></iframe>
<style>
#container {
width: 100%;
height: 800px;
}
</style>
<script src="index.js"></script>
</body>
</html>
c07.xhtml
<!DOCTYPE html>
<html>
<body>
<h1>The section element</h1>
<section>
<h2>History</h2>
<p>The World Wide Fund for Nature (WWF)</p>
</section>
<section>
<h2>Symbol</h2>
<p>The Panda has become the symbol of WWF.</p>
</section>
</body>
</html>
//index.js
const parentNode = document.querySelector("#container");
const iframeBody = iframeRef(parentNode);
console.log(element.childNodes[0].getElementsByTagName('section')); //prints HTMLCollection[] and length is 0
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
我該如何解決這個問題?
uj5u.com熱心網友回復:
試試這對我有用。訪問函式內部的 iframe dom 元素setTimeout。
const parentNode = document.querySelector("#container");
setTimeout(() => {
const iframWindow = parentNode.contentDocument;
console.log(iframWindow.getElementsByTagName("section")); //prints HTMLCollection[] and length is 0
}, 1000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481768.html
標籤:javascript dom
