Is there a way to replace the ENTIRE contents of an iframe using Javascript (or Jquery)?
For example if my iframe had the following content...
blah outside of html
<html>
<head>
</head>
<body>
<h1> my title </h1>
</body>
</html>
blah outside of html
..It could all be replaced by your script :)
The best that I've seen so far is this:
$(youriframe).contents().find('html').html('your content here');
but that still wouldn't replace the content outside of the html tags. We have an interesting scenario where we must assure that ALL the content is replaced.
OR a new iframe with fresh content is created and simply replaces the previous iframe.
Please no comments about the src attribute.
The iframe attribute "src" holds the Web address for the HTML code you want to display in a particular section of your Web page. HTML's DOM, or Document Object Model, lets you replace an iframe's HTML code by giving JavaScript's getElementById function access the "src" attribute.
IFrames are not obsolete, but the reasons for using them are rare. Using IFrames to serve your own content creates a "wall" around accessing the content in that area. For crawlers like Google, It's not immediately clear that cotent in an iframe will be ranked as highly as if the content were simply part of the page.
To remove an iframe with JavaScript, we can use the remove method. to add an iframe. to select the iframe with querySelector . And then we call remove to remove it.
I am having the same issue, and if i use the code like this:
$(youriframe).contents().find('html').html('your content here');
It works fine in Chrome or FireFox, but in IE8, nothing will be showed or the scroll bar in iframe won't appear.
If i use Rachel's method, the iframe content will be like this in all browsers:
<iframe>
<html>
<head>
</head>
<body>
</body>
</html>
</iframe>
is there any other solution?
Tried this one:
var doc = document.getElementById(iframeId).contentWindow.document;
doc.open();
doc.write(iframeContent);
doc.close();
this works on my case, both ie8 and FF/chrome.
I'm guessing that you're not having problems with cross-site scripting in this instance... Have you had any luck using contentWindow? Something like this seems to work well enough for me:
iframe = document.getElementById('iframe_id');
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(new_content_here);
Not my idea, found it here: Write elements into a child iframe using Javascript or jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With