How to execute <script> code in a javascript append

user734063 picture user734063 · Jan 11, 2013 · Viewed 25.3k times · Source

I'm working with a plugin that is only Javascript. I need to have it dynamically create a DIV element with an advertisement in it.

I can't figure out why this doesn't work:

$(this).append('<div class="overlay-background">Advertisement

     <script type="text-javascript">

          GA_googleFillSlot("blog_landing_right_rectangle_300x250");

     </script>'

It results in the element created with "Hello World" but it does not execute the GA-googleFillSlot function.

Answer

wless1 picture wless1 · Jan 11, 2013

appending HTML into the DOM does not cause the browser to evaluate any script tags in said appended HTML.

If you really wanted to, you could evaluate the javascript by using eval():

eval($(this).find("script").text());