Say I have a reference to a document object, which is contained inside an IFRAME. How do I get a reference to the container IFRAME? .parentNode and .ownerDocument both return null.
Please note that no context information is available (e.g. solutions like 'window.xxx' will not work) - all that's available is a reference to the document object.
Thanks
A document is not directly connected to its parent document. You do need a reference to
window
in order to pick up theparent
.The DOM Level 2 Views property
document.defaultView
will give you thewindow
in most modern web browsers, but in IE you have to use the non-standarddocument.parentWindow
instead. (Some older or more obscure browsers don't implement either of these properties, in which case you're stuck.)That'll give you the
window
of the parent document. If you want to get the<iframe>
that holds your document, you'll have to iterate through all the iframes on the page and check whether the contained document is yourself.Again, the method to get from an iframe element back to the child is gratuitously different in IE (
iframe.contentWindow
giving you thewindow
) vs the DOM standard and everyone else (iframe.contentDocument
giving you thedocument
).So, something like:
(The
try...
is to avoid crashing the loop out when a document access fails due to another iframe being on a different domain, causing a Same Origin Policy error.)I use this: