Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I add a string containing a script tag to innerHTML in IE

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!

like image 600
bitsprint Avatar asked Jul 01 '09 11:07

bitsprint


People also ask

Can scripts be inserted with innerHTML?

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.

Why innerHTML does not work?

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.

How do I write HTML inside innerHTML?

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() .

How do I run a script in HTML?

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.


1 Answers

you need to use escape char for the </script>

div.innerHTML = '<script src="somescript.js"><\/script>';

see why escaping / in javascript '<\/script>'?

like image 172
Scherbius.com Avatar answered Oct 30 '22 00:10

Scherbius.com