Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refer to the document object of an <iframe> from the parent page, using jQuery?

I'm trying to access the document object of a page that lives in an <iframe> from the host page. In other words, I have a page that has an <iframe> in it, and I want to use jQuery on that page (the parent page) to access the document object of that <iframe>.

Specifically, I'm trying to find the height of the <iframe>d document once its content is rendered (onload) so that I can then resize the <iframe> from the parent page to match the height of the <iframe>'s content exactly.

If it's important, this <iframe> is created on the host page using JavaScript, and is in the same domain as the parent page. I already use this type of code:

$('iframe').contents().find('body').append('<p>content</p>');

to populate the <iframe> with content, but I don't know the exact syntax for getting the <iframe>'s document object.

For some reason I'm finding a lot of ways to access the parent's document object from within an <iframe> (most with plain JavaScript), but not the other way around.

Thanks in advance for any help!

like image 411
Bungle Avatar asked Oct 15 '09 15:10

Bungle


1 Answers

$('iframe').contents().get(0)

or

$('iframe').contents()[0]

will return the document of the first iframe on the page. Remember jQuery objects are arrays of the matching DOM elements

like image 68
JeremyWeir Avatar answered Oct 13 '22 11:10

JeremyWeir