I have a page with an iframe that has an html document within it. I need to access the iframe's id from that child document, and am having no luck getting at it with jQuery. The essential structure is this within my page:
<div id="ContainingDiv">
<iframe id="ContainingiFrame">
<html>
<head></head>
<body>
</body>
</html>
</iframe>
</div>
In my javascript method I can get to anything in the <body>
tags using jQuery selectors, but cannot retrieve the iframe element in order to resize it. I've tried a few things but am admittedly not an expert in jQuery DOM navigation, particularly where iframes are involved (the iframe is in the same domain as the containing page.) Is there a way I can do this?
Try this:
To access the parent's document from your iframe you can add a parameter to your selectors, default is document but nothing prevents you from changing the context to window.parent.document like this :
Or add it before your selector :
If you do not have information about the iframe (such as an identifier to query with) then you want to use the frameElement of the window as follow:
Now you have the iframe tag itself and can work with it directly in JavaScript.
To use jQuery instead of plain JavaScript, you use the following:
We just talked about the first part (
window.frameElement
). The second part is the context in which jQuery will find the element and wrap it. This is the parent document of our current window.For example, if you have a unique id in the
iframe
tag you could do:Now
id
is the identifier if theiframe
your JavaScript code is running into.P.S. if
window.frameElement
is null or undefined, then you are not in aniframe
.P.P.S note that to run code in the parent window, you may need to use the parent instance of
jQuery()
; this is done usingwindow.parent.jQuery(...)
. This is particularly true if you try totrigger()
an event!P.P.P.S. make sure to use
window.frameElement
and not justframeElement
... some browsers are somewhat broken and they will not always be able to access the correct data if not fully qualified (although in 2016 that problem may be resolved?)Try this:
Resize some element inside
iframe
:Or just resize the
iframe
:No need for jQuery at all. To get the body object of your parent, you can do this:
If it's on the same domain as your iframe that you are running the code from, once you have that, you can use normal javascript on that object:
or with jQuery:
Here's an article on resizing an iframe from within the iframe with sample code: http://www.pither.com/articles/2010/11/12/resize-iframe-from-within
And, a related question/answer on resizing an iframe based on it's own content: Resizing an iframe based on content
If you have a reference of element within
iframe
and need to find its parentiframe
especially when you have more than one iframes, here is a way of finding it.