Link to home
Start Free TrialLog in
Avatar of Whing Dela Cruz
Whing Dela CruzFlag for Anguilla

asked on

Replacing Javascript in the head of html5

I need to to replace the head of my Html5 (<head id="H14"></head>) through js but the newly script I attached on it won't work. The link and style works fine but the newly <script></script> won't work. Is there any idea how to do this?

Original <head>
<head id="H14">
       <script src="UniJs.js"></script>
</head>

Open in new window


Javascript
var newjs = <script src="N75.js"></script>
document.getElementById('H14').innerHTML = newjs ;

Open in new window


Hi experts, After replacing, the newjs won't work, all its function as well, but the old js (N75.js) still working. Please help me how to do this. Thank you!
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is an ES5 safe version
function replaceScript(src, tgt) {
  var scripts = document.getElementsByTagName('script');
  for(var i = 0; i < scripts.length; i++) {
    var s = scripts[i];
    if (s.src.substr(-src.length) === src) {
      s.remove();
      var newscr = document.createElement('script');
      newscr.src = tgt;
      document.head.appendChild(newscr);
    } 
  }
}

Open in new window

Avatar of Whing Dela Cruz

ASKER

Thank you both of you, leakim971 and Julian Hansen, your solution is so great where it works perfectly to my project. More power and God bless to both of you!
you welcome, have a nice day!