Reputation: 1832
I'm trying to output a <script>
element in an innerHTML:
<script type="text/javascript">
function fileManager()
{
data = document.getElementById("FM");
data.innerHTML = "<script type='text/javascript' src='functions.js'></script>";
}
</script>
<div id="FM"></div>
<ul id="show-menu">
<li onClick="fileManager()">File Manager
</ul>
The innerHTML bit of the script works perfectly, it's just that there's a problem with escaping characters inside the double quotes ("). The whole <script type='text/javascript' src='functions.js'></script>
seems to be broken/written incorrectly and I can't seem to figure out what's wrong with it.
In case you're wondering, the functions.js file contains only document.write("test");
for testing purposes.
For some unknown reason this does not work. The result is a broken page, I see bits of other functions in the script and it doesn't make sense. How do I escape it correctly?
Upvotes: 3
Views: 2241
Reputation: 140230
The literal <script>
/</script>
inside the script is actually breaking the html tag that contains the script itself. There is also the problem that
.innerHTML
does not execute or load scripts. So I suggest:
function fileManager()
{
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'functions.js';
document.getElementById("FM").appendChild(script);
}
Upvotes: 4
Reputation: 1595
There is a bug in certain browsers that will mess up when you try to insert script tags using javascript. What you need to do is break up the script tags like this:
"<scr"+"ipt..........</scr"+"ipt>"
This will work.
Upvotes: 0