0

i want to execute jquery scripts in jquery html method. Like

$(body).html("<div id='mydiv'></div><script>$('#mydiv').fadeIn();</script>");

or

$(body).append("<div id='mydiv'></div><script>$('#mydiv').fadeIn();</script>");

div is inserted but javascript code not run.

How code can be runned?

3
  • 2
    What is it exactly that you want to do ? Could you be more specific ? Commented Sep 20, 2013 at 9:58
  • It's maybe because your java script is executed after the html loarding. I'm not sur you can do it with DOM Commented Sep 20, 2013 at 10:00
  • You need to explain your actual problem. You are trying to solve it in the wrong way. Commented Sep 20, 2013 at 11:23

1 Answer 1

2

You should try something like this:

$(body).append("<div id='mydiv'></div>");
$('#mydiv').fadeIn();

After first line executing there are mydiv appears in DOM, so you can access it directly from your current script.


Edit (after comments)

If you want add script to you DOM using jQuery you should do it in some tricky way:

$("<script>$('#mydiv').fadeIn();</" + "script>").appendTo(document.body);

or

$("\x3Cscript>$('#mydiv').fadeIn();\x3C/script>").appendTo(document.body);

Without escaping or breaking </script> tag it terminates the entire script.

If you have more issues with your code please refer to next answer https://stackoverflow.com/a/3603496/1430055 where you can find explanations about debugging such a dynamic script, etc.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, this is workong but iam want to put $(body).append(var); where var is variable with javascript code;
OK, in this case your question looks like duplicate. There is a detailed answer for the same question: stackoverflow.com/a/3603496/1430055
Thankyou but this is only for scripts, iam want to put mixed contents. HTML text with javascript. Javascript is working but Jquery is not working. - $(body).append("<div id='mydiv'></div><script>alert();</script>"); is working, - $(body).append("<div id='mydiv'></div><script>$('#mydiv').fadeIn();</script>"); - not working
I found another bug in your code. You are using incorrect jQuery selector for body tag. It should be enclosed in quotes. Please look at this working example: jsfiddle.net/TBW9W

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.