getElementById not changing

In a fresh browser console the following variable is expected to have undefined value:

var old = document.getElementById("loadScript");

Output is as expected: undefined

Now we add the following code:

var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.id = 'loadScript';
script.type = 'text/javascript';
script.src = 'http://server.ip/script.js';
head.appendChild(script);

Now we add the same code again:

var old = document.getElementById("loadScript");

Why the output is still null? Isn’t it supposed to get value since we changed script.id to loadScript?

On the /script.js I have just a simple code, nothing fancy: alert('Executed')

23 thoughts on “getElementById not changing”

  1. Use setAttribue to set the attributes values:

    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement('script');
    script.setAttribute('id','loadScript');
    script.setAttribute('type','text/javascript');
    script.setAttribute('src','http://server.ip/script.js');
    head.appendChild(script);
    
    Reply

Leave a Comment