dude dude - 3 months ago 6
HTML Question

Get parent iframe element by an element located within an iframe

Assuming you have the following HTML:

<div>
<iframe src="..">
<!-- The following would be the content of the iframe -->
<html><head></head><body>
<span>I'm the node</span>
</body></html>
</iframe>
</div>


And you have a variable
iframeNode
containing the
<span>
element within that iframe. Your script context is the parent window.

How would you get the parent iframe element:

<iframe src="..."></iframe>


by this node?

In theory:

var iframe = iframeNode.myParentIframeElementInTheParentScope;

Answer

If your only reference to the iframe is a span in that iframe (= iframeNode), then

var iframe = iframeNode.ownerDocument.defaultView.frameElement;

will refer to the iframe element in the parent window.