I'm trying to do the following (I'm using the prototype library):
var div = document.createElement('div');
div.innerHTML = '<script src="somescript.js"></script>';
$('banner').insert(div);
In IE, div.innerHTML property is always equal to "" after I set the property in the second line.
This snippet is inside a function which is overriding document.write() in an external vendor script, so that is why I am doing it this way rather than creating a script element and appending it to the div element directly.
Any help would really be appreciated, this is giving me grey hairs!
For anyone still trying to do this, no, you can't inject a script using innerHTML , but it is possible to load a string into a script tag using a Blob and URL.
People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.
The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
you need to use escape char for the </script>
div.innerHTML = '<script src="somescript.js"><\/script>';
see why escaping / in javascript '<\/script>'?
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