How to get document object of iframe?

Member

by ryleigh , in category: Javascript , 14 days ago

How to get document object of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 13 days ago

@ryleigh 

In order to get the document object of an iframe, you can use the contentWindow or contentDocument property of the iframe element. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
    <title>Get document object of iframe</title>
</head>
<body>

<iframe id="myIframe" src="https://www.example.com"></iframe>

<script>
    var iframe = document.getElementById('myIframe');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Now you can access the document object of the iframe
    console.log(iframeDoc);
</script>

</body>
</html>


In the script section, we first select the iframe element using document.getElementById('myIframe'). Then we check if the iframe has a contentDocument property, if not we fallback to using contentWindow.document. This will give you access to the document object of the iframe, which you can then use to manipulate its contents.