Thomson
Thomson

Reputation: 21625

How to get the element inside an iframe element in Javascript?

I have a element as below inside the document, I could get the iframe element by document.getElementById('iframe_id'), but how to get the element inside this iframe? I tried iframeElement.contentWindow, and the returned DOMWindow has no properties. Also tried iframeElement.docuemnt and iframeElement.contentDocument, both of them are undefined. How can I get it? I am using the latest Chrome in my experiment.

Here is the iframe element

<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>

Upvotes: 7

Views: 18324

Answers (3)

mplungjan
mplungjan

Reputation: 177885

You can ONLY interrogate content in an iframe if the content has the same protocol, domain and port number as the script that interrogates it. It is called SAME ORIGIN

If that is the case, then this code will show the content. If not - you cannot access the iframe from a normal script in a normal html page

Demo - tested in IE8, Chrome 13 and Fx6

function showIframeContent(id) {
  var iframe = document.getElementById(id);
    try {
      var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;
      alert(doc.body.innerHTML);
    }
    catch(e) {
       alert(e.message);
    }
  return false;
}


<iframe id='iframe_id1' src="javascript:parent.somehtml()"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id1')">Show</a>
<hr/>

<iframe id='iframe_id2' src="http://plungjan.name/"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id2')">Show</a>
<hr/>

Upvotes: 6

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22106

Having:

var iframe = document.getElementById('iframe_id');

To get the content document you can use:

var contDoc = iframe.contentDocument || iframe.contentWindow.document;

Then you can search for your element inside the iframe by id.

Upvotes: 4

dwalldorf
dwalldorf

Reputation: 1379

You should be able to access it by document.getElementById('yourIFrame').document.getElementById('yourElement')

Upvotes: 0

Related Questions