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:
- You need jQuery in the iframe if you're going to use it there.
- You must use a separate
<script>
tag for loading jQuery. You can't use both a .src
and a inline script in the same tag.
- You must use the proper
$(document).ready(function() { your code here})
syntax.
- You must break apart the
<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.
JavaScript
– Muhammad Sultan Jun 04 '14 at 18:16