Harshit Laddha
Harshit Laddha

Reputation: 2124

How to dynamically remove script from a page

What i am trying is - http://jsfiddle.net/jhrz9/1/

to remove the script generated when someone clicks the button #goBack button Now i am able to create and append script and style tags when the user clicks the #runMyCode But as soon as i go back to the previous screen using #goBack button the script stays on the screen, now what i want to do is to remove that script and create another one again when i click the #runMyCode button

Now i am trying this -

var newScript = document.createElement('script'); ;
var newTextNode=document.createTextNode($("#jsTextArea").val());
newScript.type = 'text/javascript';
newScript.appendChild(newTextNode);
document.body.appendChild(newScript);
$('#goBack').click(function(){
newTextNode.parentNode.removeChild(newTextNode);
});

But for some reason it is not working....

Upvotes: 1

Views: 9547

Answers (1)

Dvir
Dvir

Reputation: 3339

you have to give the script an id.

$("#runMyCode").click(function(){
   $("#resultContainer").html($("#htmlTextArea").val());
   var newScript = document.createElement('script');
   newScript.id = "goback_script";
   var newTextNode=document.createTextNode($("#jsTextArea").val());
   newScript.type = 'text/javascript';
   newScript.appendChild(newTextNode);
   document.body.appendChild(newScript);
   var newStyle = document.createElement('style');
   var newTextNode2=document.createTextNode($("#cssTextArea").val());
   newStyle.type = 'text/css';
   newStyle.appendChild(newTextNode2);
   document.body.appendChild(newStyle);
});
$('#goBack').click(function(){
   var script = document.getElementById("goback_script");
   script.parentElement.removeChild(script);
});

jsFiddle

Upvotes: 1

Related Questions