I write jQuery script inside my iframe to hide h1 inside the iframe
<iframe id = "preview" width="800" height="500">
</iframe>
<script>
var H = "<html><head><script>$(\'#hh\').toggle();<";
H+= "/script></head><body><h1 id='hh'>JavaScript</h1></body></html>";
var previewFrame = document.getElementById("preview");
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(H);
preview.close();
</script>
but,the script can't see the elements inside the iframe. when I moved the element with id='hh' out of the iframe, the script works.
It looks like you're trying to use jQuery inside the iframe for the script you're putting in the iframe, but you don't have jQuery in the iframe. The iframe is a whole different execution context. If you want to use jQuery in there, you have to load jQuery in there.
Also, you can't run a script that tries to modify the DOM from the <head>
element. The DOM isn't loaded yet. You have to either move that script after the content in the <body>
(e.g. right before </body>
) or use $(document).ready(...)
to run the script AFTER the DOM is ready.
OK, this is the sum of issues I found:
<script>
tag for loading jQuery. You can't use both a .src
and a inline script in the same tag.$(document).ready(function() { your code here})
syntax.<script>
and </script>
that is in your JS string so the browser doesn't interpret it like '<scr'
+ 'ipt>'
.This works for me:
var H = '<html><body><h1 id="hh">JavaScript</h1>';
H += '<scr' + 'ipt src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scr' + 'ipt>';
H += '<scr' + 'ipt>$(document).ready(function() {';
H += '$("#hh").hide();';
H += '});</scr' + 'ipt>';
H += '</body></html>';
var previewFrame = document.getElementById("preview");
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(H);
preview.close();
I've broken up your H
variable to make it more readable and easier to spot errors.
Working demo: http://jsfiddle.net/jfriend00/8L3KT/
FYI, this is the painful way to do this. Creating a full HTML document in JS is easy to make mistakes with.
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