Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById.contentDocument error in IE

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

like image 382
mm. Avatar asked Sep 25 '09 14:09

mm.


2 Answers

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.

like image 156
Crescent Fresh Avatar answered Nov 02 '22 01:11

Crescent Fresh


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; 
like image 12
RaYell Avatar answered Nov 02 '22 00:11

RaYell