I am trying to get a div from within an iframe and print it on my page. Any Ideas ?
+8
A:
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.)
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.
geowa4
2009-07-06 18:35:36
Great answer. Did you know that you can do: var innerDoc = iframe.contentDocument || iframe.contentWindow.document; //more readable and means the same
David Caunt
2009-07-06 18:40:20
yeah, i did know about that.
geowa4
2009-07-06 18:42:51
I've seen people confused by that more than ternary operators. They seem to not know that the first valid one is returned.
geowa4
2009-07-06 18:44:04
in fact, as i edited the answer to include it, the guy over my shoulder asked me what that did...
geowa4
2009-07-06 18:46:35
Probably better to educate than use more complex code for simplicity :)
David Caunt
2009-07-07 11:28:07