views:

2283

answers:

5
<html>
   <script type="text/javascript">
      function func() {
         alert(document.getElementById('iView').contentDocument);
      }    
   </script>
   <body>
      <iframe id="iView" style="width:200px;height:200px;"></iframe>
      <a href="#" onclick="func();">click</a>
   </body>
</html>

After click, Firefox returns [object HTMLDocument]. Internet Explorer returns undefined.

How can I select the iView element with Internet Explorer? Thanks.

A: 

You seem to want to get the contents of the iframe right?

IE7 and FF2:

var iframe = document.getElementById('iView');
alert(iframe.contentWindow.document.body.innerHTML);
thephpdeveloper
+4  A: 

From this page:

Mozilla supports the W3C standard of accessing iframe's document object through IFrameElm.contentDocument, while Internet Explorer requires you to access it through document.frames["name"] and then access the resulting document.

So you need to detect the browser and on IE do something like this instead:

document.frames['iView'].document;
RaYell
+7  A: 

The cross-browser equivalent to contentDocument (including Firefox itself, where contentDocument does work) is contentWindow.document.

So try:

alert(document.getElementById('iView').contentWindow.document);

contentWindow gets you a reference to the iframe's window object, and of course .document is just the DOM Document object for the iframe.

Here's an article that summarizes better.

Crescent Fresh
A: 

Use feature detection, as contentDocument is supported in IE 8:

var iframe = document.getElementById("iView");
var iframeDocument = null;
if (iframe.contentDocument) {
    iframeDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
    // for IE 5.5, 6 and 7:
    iframeDocument = iframe.contentWindow.document;
}
if (!!iframeDocument) {
    // do things with the iframe's document object
} else {
    // this browser doesn't seem to support the iframe document object
}
NickFitz
A: 

there is a bug - two exclamation marks, should be one. but doesn't work anyway

wolo