Home > Blockchain >  Failed to traverse DOM while rendered inside iframe with section tags
Failed to traverse DOM while rendered inside iframe with section tags

Time:05-27

I facing a situation which i can't traverse the dom inside iframe. My code is as follows. When i am trying to accessing childNodes of body tag, console will show there are no childNodes inside the body tag.

<!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
}

How can i resolve this?

CodePudding user response:

Try this its working for me. Access iframe dom elements inside setTimeout function.

const parentNode = document.querySelector("#container");
setTimeout(() => {
  const iframWindow = parentNode.contentDocument;
  console.log(iframWindow.getElementsByTagName("section")); //prints HTMLCollection[] and length is 0
}, 1000);
  • Related