I have created a DIV dynamically and I want it to contain a JavaScript link, that will output something on it. The JavaScript link source is absolute. Obviously, this doesn't work:
var div = document.createElement('div');
div.id = 'mydiv';
div.innerHTML = "<script type='text/javascript' " +
"src='http://mydomain.com/myscript.js'></script>";
document.body.appendChild(div);
so I tried this one
var script = document.createElement('script')
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://mydomain.com/myscript.js');
var div = document.createElement('div');
div.id = 'mydiv';
div.appendChild(script);
document.body.appendChild(div);
In my script file I have a simple alert('Testing...');
code.
The problem is that it doesn't work. The script inclusion is typed inside the div (I see it when I inspect the DIV in Chrome), but it doesn't work. I don't see the 'Testing...' message.
What am I missing or doing wrong? Thanks!
document.getElementById('id-of-your-div').innerHTML('Loading...')
? Also, you could just have the div be<div id='some-id'>Loading ...</div>
to start with and then the script can write to its innerHTML. The script need not be contained within the div, and in fact, shouldn't because you might overwrite it depending on what you're doing to the contents of your div. – Kasapodocument.write
without blowing your whole page away, even if you do get the script to run, if you're doing this stuff after the DOM is built. You should generally avoiddocument.write
anyway; manipulating the DOM directly would make much more sense. – Pointysrc
attribute by aninnerHTML
as I wouldn't host a JS just for an alert, try adapting it and make sure your script's source is right. – Fabrício Matté