Get element from within an iFrame Get element from within an iFrame javascript javascript

Get element from within an iFrame


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.)

IMPORTANT: 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.


Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe><script>function access() {   var iframe = document.getElementById("iframe");   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;   console.log(innerDoc.body);}</script>


Above answers gave good solutions using Javscript.Here is a simple jQuery solution:

$('#iframeId').contents().find('div')

The trick here is jQuery's .contents() method, unlike .children() which can only get HTML elements, .contents() can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it.

Further reading about jQuery .contents(): .contents()

Note that the iframe and page have to be on the same domain.