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
1 Answer
Reset to default 6You 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条)