How do you get a <div>
from within an <iframe>
?
contents() can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it. Note that the iframe and page have to be on the same domain.
In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.
To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document. getElementById() method by passing iframe id as an argument. const iframe = document.
The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.
var iframe = document.getElementById('iframeId'); var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
You could more simply write:
var iframe = document.getElementById('iframeId'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
and the first valid inner doc will be returned.
Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById
...etc.)
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.
Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe> <script> function access() { var iframe = document.getElementById("iframe"); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; console.log(innerDoc.body); } </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With