How to set HTML content into an iframe
You could use:
document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");
Here's a jsFiddle, which works in all major browsers.
Note that instead of contentDocument.write
you should use contentWindow.document.write
: this makes it work in IE7 as well.
var htmlString="<body>Hello world</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src="javascript:'"+htmlString+"'";
With html5 you'll be able to use the srcdoc attribute.
The innerHTML
is a bit tricky especially in IE, where elements like thead
are read-only and cause a lot of trouble.
Based on the documentation on msdn you might try documentMode
which provides a innerHTML
property.
myIFrame = myIFrame.contentWindow ||
myIFrame.contentDocument.document ||
myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write('Your HTML Code');
myIFrame.document.close();
this might only work in IE.
- http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
- http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
- http://msdn.microsoft.com/en-us/library/ie/ms533897(v=vs.85).aspx
How about document.documentElement.innerHTML
. But do know that everything in the page will be replaced even the script that does that.
For an iframe it would be like this myIFrame.contentWindow.document.documentElement.innerHTML