How to Remove a Script from the DOM in JavaScript

There are plenty of times I find myself looking to remove a script from the DOM. Some common reasons to remove scripts from the DOM include:

  • The script is execution blocking
  • The script is no longer valid and points to an invalid resource
  • Duplicate scripts exist on the page and one has to be removed
  • Removing scripts if a response is empty
  • A script exists on the page and you don’t have access to the source code so you need to dynamically remove it via JavaScript

So with these use cases and others in mind, how can you remove a script from the DOM in JavaScript?

We can remove a script from the DOM by scanning through all scripts on the page, getting the parent node of that script, and then finally removing the child of that parent node.

Let’s say we have a script on the page like so:

<script id="my-test-script" type="application/javascript">
 alert("Hello World!")
</script>

 We want to scan through all possible scripts with type application/javascripton the page:

const scriptList = document.querySelectorAll("script[type='text/javascript']")

This returns us a NodeList of scripts:

We need to convert this NodeList to an array in order to iterate through it:

const convertedNodeList = Array.from(scriptList)

Now, lets use .find()to get our specific script by its id:

const testScript = convertedNodeList.find(script => script.id === "my-test-script")

Here is the interesting part. We want to remove this script by self referencing it from its own parentNode.

testScript.parentNode.removeChild(testScript)

And there you have it! This is a nice and concise way of removing a script from the DOM. I hope this helped.

Proudly published with Gatsby