I would like to load an iframe with dynamic html and script, and then execute it. In my html document I have this simple iframe tag:
<iframe></iframe>
And my jQuery script, which loads on Document Ready, and is supposed to prepare the iframe:
$( document ).ready(function() {
// Add jQuery lib
$('iframe').contents().find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>)');
// Add div to body
$('iframe').contents().find('body').html('<div id="myDiv">Initial</div>');
// Add script to change div
$('iframe').contents().find('body').html('<script>$("#myDiv").html("Changed")</script>');
});
The above jQuery script should do the following inside the iframe:
- Load the jQuery library
- Setup a div in body with a simple text in it
- Setup a jQuery script in body, where I use a jQuery selector to change the content of the div
But I don't get very far, as the console window says:
Uncaught SyntaxError: Unexpected token ILLEGAL
What I want with this question is to know how I can get the script inside the iframe to change its div's text to "Changed".
I have created a jsFiddle.
* UPDATE *
I don't see how this is a duplicate of Script tag in JavaScript string, which is about parsing strings in javascript. What my questions is about, is how I can load dynamic html and jQuery in an iframe and afterwards execute the script.