Search code examples
javascriptjqueryiframe

Write elements into a child iframe using Javascript or jQuery


I have something like this:

<!doctype html>
<html>
  <body>
     <iframe id="someFrame"></iframe>
  </body>
</html>

And I would like to use jQuery to write elements such that the full equivalent HTML would be like this:

<!doctype html>
<html>
  <body>
    <iframe id="someFrame">
      <!-- inside the iframe's content -->
      <!-- <html><body>  -->
      <div>A</div>
      <div>B</div>
      <div>C</div>
      <!-- </body></html> -->
    </iframe>
  </body>
</html>

Alternatively, any plain-old-Javascript would be fine.

Thanks.

Edit: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. "contentDocument" is a W3C standard which FF supports, but IE does not. (surprise surprise)


Solution

  • You can do both, you just have to target differently:

    var ifrm = document.getElementById('myIframe');
    ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;
    ifrm.document.open();
    ifrm.document.write('Hello World!');
    ifrm.document.close();