Scott Paterson
Scott Paterson

Reputation: 151

Remove JavaScript code from page with JavaScript

I have a chunk of JavaScript code:

 <script src='blah.js' type='text/javascript'></script>

How can this be removed or disabled with JavaScript?

Upvotes: 0

Views: 2015

Answers (2)

dsan
dsan

Reputation: 1588

You can grab the script like any other element, you can do this:

document.querySelector("script").remove();

If you have a lot of script tags you can just grab the one you want like accessing a array element like so:

document.querySelectorAll("script")[1].remove();

The code above removes the second script tag in a page.

Upvotes: 0

Amadan
Amadan

Reputation: 198526

If the script tag is received in a string via AJAX:

str = str.replace("<script src='blah.js' type='text/javascript'></script>", "");

However, if the script tag is in the current document, there is no way to disable it, because:

  • If it is in the part of the document which has already been parsed (i.e. above the current script), it has already been executed. While you can remove the script element, just like any element, there is no way to rewind time and automatically undo the effects the script has.

  • If it is in the part of the document which has not yet been parsed (i.e. below the current script), you cannot affect it, as it does not exist yet.

Upvotes: 1

Related Questions