Insert content into iFrame

I am trying to insert some content into a 'blank' iFrame, however nothing is being inserted.

HTML:

<iframe id="iframe"></iframe>

JS:

$("#iframe").ready(function() {
    var $doc = $("#iframe").contentWindow.document;
    var $body = $("<body>").text("Test");
    $body.insertAfter($doc);
});

I am calling the ready function so I don't understand why it is not inserting.


Solution 1:

You really don't need jQuery for that:

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();

jsFiddle Demo

If you absolutely have to use jQuery, you should use contents():

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append('Test');
});

jsFiddle Demo

Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:

$(function() {  
    var $iframe = $('#iframe');
    $iframe.ready(function() {
        $iframe.contents().find("body").append('Test');
    });
});

Solution 2:

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');