remove appended script javascript

Robin Carlo Catacutan picture Robin Carlo Catacutan · Feb 22, 2012 · Viewed 41.2k times · Source

how can I remove my appended script because it causes some problems in my app.

This is my code to get my script

var nowDate = new Date().getTime();
var url = val.redirect_uri + "notify.js?nocache=" + nowDate + "&callback=dummy";
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);

Then I have an auto load function, that causes to create another element script.

I want to get rid of the previous element that was appended before another element is added.

Answer

Pavel Podlipensky picture Pavel Podlipensky · Feb 27, 2012

Basically you can remove script tag by using a function similar to this one:

function removeJS(filename){
 var tags = document.getElementsByTagName('script');
 for (var i = tags.length; i >= 0; i--){ //search backwards within nodelist for matching elements to remove
  if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(filename) != -1)
   tags[i].parentNode.removeChild(tags[i]); //remove element by calling parentNode.removeChild()
 }
}

Note, it use filename parameter to identify target script to remove. Also please note that target script could be already executed at the time you're trying to remove it.