Can I create an empty iframe as a placeholder to later insert html into it?
In otherwords, suppose I have an empty iframe with an id,
How do I insert html i
Yes I know that is possible but the main problem is that we cannot handle a frame from outside it i has already loaded some other thing.
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
but if we start as
<iframe src="http:/www.hamrobrt.com">
<---Your Script to put as you like--->
Then its impossible to hit that out.
iframeElementContainer = document.getElementById('BOX_IFRAME').contentDocument;
iframeElementContainer.open();
iframeElementContainer.writeln("<html><body>hello</body></html>");
iframeElementContainer.close();
View the source of this page: http://mg.to/test/dynaframe.html It appears to do exactly what you want to do.
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
No it's not. You would modify the script like this:
$(function() {
var $frame = $('iframe');
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
You can do it without jQuery also:
var iframe = document.getElementById('iframeID');
iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);
iframe.document.open();
iframe.document.write('Hello World!');
iframe.document.close();
jQuery's html strips body, html and head tags from the inserted HTML.
I have same problem, Where I have to show html code snippet in iframe dynamically from database without SRC attribute of iframe and I fixed same problem with following code
I hope this would help someone who has same requirement I had.
jsfiddle example here
HTML :
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
JS
<script>
var doc,$body;
var txt = Array(
'<style>body{background-color:grey} h1{background-color:red;font-weight:900}</style><h1>Cool!!! this is text for</h1><p>First Iframe</p>',
'<style>body{background-color:pink}h1{background-color:green;font-weight:200}</style><h1>Cool This is Text for</h1><p> second Iframe',
'<style>body{background-color:yellow}h1{font-weight:400}</style><h1>Cool..... This is text FOR : </h1> <div>3rd Iframe</div>',
'<style>body{background-color:blue} h1{font-weight:400}</style><h1>Cool This is text for Fourth iframe</h1>'
);
$('.iframe').each(function(index,value){
doc = $('iframe')[index].contentWindow.document;
$body = $('body',doc);
$body.html(txt[index]);
});
</script>