Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific <script> tag in <head> tag by onclick event

Tags:

<head>      <script type="text/javascript">          function include(filename, status){             if(status == 'on'){                 var head = document.getElementsByTagName('head')[0];                  script = document.createElement('script');                 script.src = filename;                 script.type = "text/javascript";                  head.appendChild(script);             } else {                // The code that wipes the script tag above             }         }      </script>  </head>  <body>     <input type="button" value="OPEN" onclick="include('script.js', 'on')">     <input type="button" value="CLOSE" onclick="include('', 'off')"> </body> 

I want to remove the specific tag in tag by onclick event. What code should be written in the ELSE area, When I click the "CLOSE" botton?

like image 518
Aviway Avatar asked Feb 05 '13 13:02

Aviway


People also ask

How do I remove the DOM script tag?

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.

Does script tag go in head or body?

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

Can you put script tags in head?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body. JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked.


1 Answers

The easiest way, would be to somehow maintain a link to the created element. For example, you could put the include function into a closure and have a private variable, to hold the reference:

var include = (function(){    // the reference to the script    var theScript;     return function (filename, status){      if(status == 'on'){        // adding a script tag        var head = document.getElementsByTagName('head')[0];         theScript= document.createElement('script');        theScript.src = filename;        theScript.type = "text/javascript";         head.appendChild( theScript )      }else{        // removing it again        theScript.parentNode.removeChild( theScript );      }    } })(); 

One important note: By removing the <script> tag, you do not remove any of its objects, functions etc. from the DOM. So any action started within that <script> tag will prevail, even if you delete the element, that started it in the first place!

like image 185
Sirko Avatar answered Oct 15 '22 00:10

Sirko