Reputation: 523
I am developing a small editor to add widgets (HTML, CSS and Javascript) to a site.
Except that I have a problem to retrieve the javascript code. Indeed, it is well executed, but disappears from the DOM. There is something that escapes me!
I simplified my problem here: HTML code:
<textarea id="code">
<script type="text/javascript">alert("code");</script>
</textarea>
<div id="target"></div>
Javascript code:
$("#target").html($("#code").val());
alert($("#target").html());
Try it out : http://jsfiddle.net/8uhB8/3/
This example insert javascript code (a simple javascript alert) and tries to retrieve it.
Do you have any idea?
Thanks!
Upvotes: 2
Views: 406
Reputation: 781706
That's how .html()
works. It assigns .innerHTML
with all the structural parts of the HTML. But assigning innerHTML
doesn't execute scripts. So jQuery pulls all the scripts out of the HTML, and puts them in a <script>
node to execute them. This node is only temporary, and is removed by the time .html()
completes. But the scripts are still executed.
Upvotes: 2
Reputation: 28505
$("#target").html($("#code").html());
alert($("#target").html());
Because you are using HTML characters you need to use .html()
in this case.
Upvotes: 2