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.
append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')
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());
I know this is an old question but I've had a similar problem today. The solution was using createContextualFragment.
My code looks something like this:
var tagString = '<script async type="text/javascript" src="path_to_script"></script>';
var range = document.createRange();
range.selectNode(document.getElementsByTagName("BODY")[0]);
var documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);
This code works in my browser.
$('body').append('<script>alert("test");<' + '/' + 'script>');
so it might be that $(this)
is what is actually causing your problem.
Can you replace it with 'body'
and see if it works like that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With