'Set iframe innerHTML without loading page in it (with jquery)

I want to set the contents of an iframe dynamically, when no pages were loaded before in the iframe.

I'm doing that :

iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml';
$('body').append(iframe);

iframe
.contents()
.html(iframeHtml);

But it is not working, the html is still empty.



Solution 1:[1]

If you want to avoid using document.write, which is generally not recommended any longer, you can get at the frame contents to add the content:

iframe = $('<iframe id="thepage"></iframe>')
iframeHtml = 'iframeHtml'
$('body').append(iframe)
iframe.contents().find('body').html(iframeHtml)

Solution 2:[2]

Using JQuery, you can edit the iframe's attribute srcdoc by passing it the html as string:

$('#iframe_id').attr("srcdoc", htmlString);

Solution 3:[3]

iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml'; $('body').append(iframe);

iframe .contents() .html(iframeHtml);

the reason it does not work is because contents() returns a document object and html() only works on HTMLElemnt objects, html() is basically a wrapper around innerHTML property and document does not have such property.

Solution 4:[4]

Use the jQuery contents() method.

You can use the jQuery contents() method in combination with the find(), val() and html() methods to insert text or HTML inside an iframe body.

var EditFrame = $("#EditWindow").contents().find('body');  
var message = "Your message which needs to show in Iframe";
EditFrame.html(message);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Schneider
Solution 2
Solution 3 Alfgaar
Solution 4 Skeets