I have the following HTML / JS:
<html> <body> <script> function foo(){ var html = '<iframe src=\'foo.html\' />'; document.getElementById('content').innerHTML=html; } function bar(){ var html = '<iframe src=\'bar.html\' />'; document.getElementById('content').innerHTML=html; } function show(){ alert(document.getElementById('content').innerHTML); } </script> <button onclick='foo()'>foo</button><br /> <button onclick='bar()'>bar</button><br /> <button onclick='show()'>test</button><br /> <div id='content'></div> </body> </html>
This sort of works as expected, even in IE. Until I hit F5. When I first click foo, I get an iframe with the contents of foo.html, as expected. I then refresh, and hit bar. Instead of getting the contents of bar.html, I see the contents of foo.html. Strangely, when I click test, the alert() tells me the src attribute for the iframe is correctly set to bar.html. Firefox has no such issue.
Why does this happen, and how do I prevent it?
edit: what I forgot to mention is that I can’t put the iframe in and change the src attribute. In the real situation I have, sometimes I need an <img> rather than an <iframe>.
Have you tried changing the url in your generated iframe? E.g.
Even better, combine that with geowa4’s appendChild() suggestion.