javascript - Iframe body when accessed through iframeElement.contentDocument.body is an empty node - Stack Overflow

I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) wher

I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) where I have a main page

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Mockup</title>
</head>
<body>
  <iframe src="./nested.html" id="frame"></iframe>
  <script>
    var iframe = document.getElementById('frame');
    console.log(iframe.contentDocument.body);
  </script>
</body>
</html>

and a nested page

<html>
    <body>
        <div id="hello">Hello, World</div>
    </body>
</html>

when I load the main page in my browser the output written to console is: <body></body> I can access the element #hello using iframe.contentDocument.getElementById('hello') but I want the body element including child elements. Can anyone please explain to me why is this happening

I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) where I have a main page

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Mockup</title>
</head>
<body>
  <iframe src="./nested.html" id="frame"></iframe>
  <script>
    var iframe = document.getElementById('frame');
    console.log(iframe.contentDocument.body);
  </script>
</body>
</html>

and a nested page

<html>
    <body>
        <div id="hello">Hello, World</div>
    </body>
</html>

when I load the main page in my browser the output written to console is: <body></body> I can access the element #hello using iframe.contentDocument.getElementById('hello') but I want the body element including child elements. Can anyone please explain to me why is this happening

Share Improve this question asked Nov 11, 2019 at 13:08 Fr3ddyDevFr3ddyDev 4741 gold badge6 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You have to wait until iframe loaded pletely to access it's body.

var iframe = document.getElementById('frame');

iframe.onload = function () {
    console.log(iframe.contentDocument.body);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744987263a4604684.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信