Reputation: 196
I hope you have well with nice pleasure. I am trying to remove Script tag by ID. For this purpose, I am apply code
var elem = document.getElementById("sns_scripts");
elem.remove();
But, this is give me error on my console windows is :
Uncaught TypeError: Cannot read property 'remove' of null
I am trying another method is :
$("#sns_scripts").remove();
It is also not working. See Picture
Picture is mention , sns_scripts script still avaialbe, and above this script my custom code, but it is not working. Please help me, I am really want to remove sns_scripts script from my webpage.
Upvotes: 0
Views: 4466
Reputation: 7094
Let's say you have a script in your DOM, with custom attribute: data-scriptid="MyDomScript"
:
<script src="jquery-3.6.0.min.js" data-scriptid="MyDomScript"></script>
Then you can remove it programmatically like this:
let domScripts = document.querySelectorAll('[data-scriptid="MyDomScript"]');
domScripts.forEach(function(s) {
s.remove();
});
Note that this will only remove the script tag from DOM, but not completely erase the variables or events already defined by the script. You have to clear them manually.
Upvotes: 0
Reputation: 182
NOTE: Re-order following lines in your code. Because you are running remove() function before writing script with id(sns_script):
<script type="text/javascript" id="sns_scripts">var video=document.getElementById('bgvid');</script>
<script>
$('#sns_scripts').remove();
</script>
Upvotes: 0
Reputation: 74738
Wrap your code within DOMContentLoaded
event:
document.addEventListener('DOMContentLoaded', function(){
var elem = document.getElementById("sns_scripts");
elem.remove();
});
Because you are trying to get an element at that point where is wasn't available in the DOM. So, it was null.
Upvotes: 6