tags:

views:

129

answers:

4
var testdiv = '<div id="hello"><p>hiii</p>
               <script type="text/javascript">some javascript functions</script>
               </div>';
$(testdiv).appendTo(document.body);

After running above code, div that is added is missing javascript, i.e everything inside < script type="text/javascript" >

Is this known issue with appendTo ?

A: 

If you're trying to include some remote script, you may have more success using $.getScript()

More info here: http://docs.jquery.com/Ajax/jQuery.getScript

Edit:

Maybe this question has the answer you're looking for?

jonscottclark
Thanks, I not using remote script.
Kurund Jalmi
A: 

Do you want to load JavaScript dynamically?

Upper Stage
I already have content(html) in javascript object.
Kurund Jalmi
Could you append that content to the new DIV?
Upper Stage
$('hello').appendTo(someContent)?
Upper Stage
I don't have <div> in dom object, so I am creating new div with this content.
Kurund Jalmi
I understand. Create the first div as you did above, and then append to it the HTML content you have contained in your JS object. Use two appendTo statements.
Upper Stage
Tired, not working :(
Kurund Jalmi
+2  A: 

You might need to chop up the <script> tags. This works:

var testdiv = '<div id="hello"><p>hiii</p><scr'+'ipt type="text/javascript">console.log("buu")</scr'+'ipt></div>';
$(testdiv).appendTo(document.body);
David
I am not sure I can do that.. since I have entire content.
Kurund Jalmi
A: 
var testdiv = '<div id="hello"><p>hiii</p><script type="text/javascript">alert(\'foo\')</script></div>';
$(testdiv).appendTo(document.body);

I replaced "some javascript" with an alert, and it works fine for me. Note that I had to escape the quotes I was using in the string, that may have been it.

I agree with jonscottclark about getScript(). There are indeed much better ways to include and execute additional scripts.

bibby
thanks, now I have changes my programming logic for this problem ...
Kurund Jalmi