简体   繁体   中英

Remove script tag from html and from the DOM with JS

How to remove a js script from the html and from the DOM?

To exemplify, in my html i have a div with a button:

<div class="tester">

    <button id="myBtn">Click me!</button>

</div>

And it has also this script <script src="js/debug.js" id="debug_js"></script>

The code of debug.js :

window.addEventListener("DOMContentLoaded", initApp1);


function initApp1()
{

    console.log("Init App!! ");

    var myBtn = document.getElementById("myBtn");
    var script = document.getElementById("debug_js");

    myBtn.addEventListener("click", function(){

        alert("clicked!");

        $( script ).remove();

    });

} //    initApp1

When i do the first click, it removes the script from the html. Ok. When i click again i expect this behaviour: DOn't make the alert "clicked!" (actually Do nothing).

The behaviour that i'm having: It throws the alert "clicked!" again (every time the btn is clicked)

After some search i found that: " By removing the tag, you do not remove any of its objects, functions etc. from the DOM. So any action started within that tag will prevail, even if you delete the element, that started it in the first place! "

So how can i remove it also from the DOM ? (or other suggestions)

You can check for the script in the button click event

var myBtn = document.getElementById("myBtn");

myBtn.addEventListener("click", function(){
    var script = document.getElementById("debug_js");
    if(script){
        alert("clicked!");

        $( script ).remove();
    }
}); 

Or you can remove the event handler after clicking

var myBtn = document.getElementById("myBtn");
var script = document.getElementById("debug_js");

var btnHandler = function(){
    alert("clicked!");
    $( script ).remove();
    myBtn.removeEventListener("click", btnHandler);
}

myBtn.addEventListener("click", btnHandler);

There are two general approaches to remove all script tags from HTML with Javascript :

REGEX

const patt = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script\s*>/gi
const html = document.getElementsByTagName('html')[0]
html.innerHTML =  html.innerHTML.replace(patt, '')

Insert it as the innerHTML of a div , see here

But... any script which got evaluated once by the engine will stay in memory for the rest of your session. Even by removing the entire script node where the code was contained doesn't change that fact.

To get rid of the script effect you can choose at least two strategies:

  • document.write(html.innerHTML); after cleaning html.innerHTML from scripts (see above)
  • clean eventListeners by EventTarget.removeEventListener()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM