Write elements into a child iframe using Javascript or jQuery

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();

After some research, and a corroborating answer from Mike, I've found this is a solution:

  var d = $("#someFrame")[0].contentWindow.document; // contentWindow works in IE7 and FF
  d.open(); d.close(); // must open and close document object to start using it!

  // now start doing normal jQuery:
  $("body", d).append("<div>A</div><div>B</div><div>C</div>");

There are two reliable methods to access the document element inside an iframe:

1. The window.frames property:

var iframeDocument = window.frames['iframeName'].document; // or // var iframeDocument = window.frames[iframeIndex].document;

Demo


2. The contentDocument property:

var iframeDocument = document.getElementById('iframeID').contentDocument; // or // var iframeDocument = document.getElementById('iframeID').contentWindow.document;

Demo


I am going out on a limb here and suggest that the answers proposed so far are not possible.

If this iframe actually has a src="somepage.html" (which you ought to have indicated, and if not, what is the point of using iframe?), then I do not think Jquery can directly manipulate html across frames in all browsers. Based on my experience with this kind of thing, the containing page cannot directly call functions from or make any sort of Javascript contact with the iframe page.

Your "somepage.html" (the page that loads in the iframe) needs to do two things:

  1. Pass some kind of object to the containing page that can be used as a bridge
  2. Have a function to set the HTML as you desired

So for example, somepage.html might look like this:

<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
    var bridge={
        setHtml:function(htm) {
            document.body.innerHTML=htm;
        }
    }

    $(function() { parent.setBridge(bridge); });

//--></script>
</head>
<body></body>
</html>

and the containing page might look like this:

<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
var bridge;
var setBridge=function(br) {
    bridge=br;
    bridge.setHtml("<div>A</div><div>B</div><div>C</div>");
    }
//-->
</script>
</head>
<body><iframe src="somepage.html"></iframe></body>
</html>

This may appear a bit convoluted but it can be adapted in a number of directions and should work in at least IE, FF, Chrome, and probably Safari and Opera...