Insert content into iFrame
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');
Wait, are you really needing to render it using javascript?
Be aware that in HTML5 there is srcdoc
, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)
See here [srcdoc
]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp
Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox
mode.
See here [sandbox
]: https://www.w3schools.com/tags/att_iframe_sandbox.asp
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');
});
});
You can enter (for example) text from div into iFrame:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append($('#mytext'));
});
and divs:
<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>
and JSFiddle demo: link