How to replace entire contents of iframe?
This question didn't receive any satisfactory answers, so I'm asking again.
I can get my iframe like this:
var iframe = document.getElementById('preview');
var win = iframe.contentWindow;
var doc = win.document;
And write some initial HTML to it like this:
doc.write('<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="reset.css"></head><body>blah blah</body></html>');
And that works great, but now I want to replace the entire thing with some new content. How can I do that?
To be clear, by "entire thing" I mean the <head>
too. I need to link some exter开发者_JS百科nal JS and CSS there.
Preferably, this would also include the <!DOCTYPE>
, but it's non-essential at this point.
You could simply remove the old iframe node from the DOM and create a new one containing the new contents.
I believe using innerHTML should work:
doc.documentElement.innerHTML = "<script src='blah.js'></script><style></style>"
精彩评论