<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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With