GetElementById.contentDocument erreur dans 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> 

Après un clic, Firefox retourne [objet HTMLDocument]. Internet Explorer retourne indéfini.

Comment puis-je sélectionner l'élément iView avec Internet Explorer? Merci.

De cette page :

Mozilla prend en charge la norme W3C d'accès à l'objet de document iframe via IFrameElm.contentDocument, tandis que Internet Explorer vous oblige à accéder à document.frames ["nom"], puis accédez au document résultant.

Donc, vous devez détecter le navigateur et sur IE faire quelque chose comme ceci à la place:

 document.frames['iView'].document; 

Le cross-browser équivalent à contentDocument (y compris Firefox lui-même, où contentDocument fonctionne) est contentWindow.document .

Alors essayez:

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

contentWindow vous fait référence à l'objet de la window l'iframe, et bien sur .document est juste l'objet Document DOM de l'iframe.

Voici un article qui résume mieux .

Vous semblez vouloir obtenir le contenu de l'iframe correctement?

IE7 et FF2:

 var iframe = document.getElementById('iView'); alert(iframe.contentWindow.document.body.innerHTML); 

Utilisez la détection des fonctionnalités, car contentDocument est pris en charge dans 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 } 
 contentWindow.document.body.innerHTML 

Fonctionne pour moi dans Internet Explorer et Firefox, alors que

 contentDocument.body.innerHTML 

Ne fonctionnera que dans Firefox.

Faites quelque chose comme ceci:

 var myFrame = document.getElementById('iView'); var frameDoc = myFrame.contentDocument || myFrame.contentWindow; if (frameDoc.document){ frameDoc = frameDoc.document; } alert(frameDoc); 

Consultez cette page pour plus de détails