Question: How to remove any JavaScript code (functions, variables, events etc.) which is Inside a Dom element (div)
Note: This is not similar question like removing content from Dom element.
My Scenario:
My site has a menu. When I click on a menu item I am loading corresponding html file which also contains JavaScript code inside a div element(id=content).
When click on menu I am doing following code
function changeMenu(params){
//need something here to remove previous js codes before load the file
$('#content').load(params['file'],function (){
///ohters code
})
}
It is working fine for first click and executing the JavaScript code as well inside that file.
But problem is it also increase executing JavaScript code number of times I click on the menu. Also when I load another file still previous JavaScript code executing because I had interval function there. Aslo if there is variable declared like this let x=10
it showing follwing error when I click the menu again
Uncaught SyntaxError: Identifier ‘x’ has already been declared
Asking Solution:
Is it posible remove all JavaScript codes when I click on the menu and How?
Sample Code
index.html
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<header>
<button onclick="changeMenu('a.html')">Load A</button>
<button onclick="changeMenu('b.html')">Load B</button>
</header>
<div id="content">
</div>
<script>
function changeMenu(file){
$('#content').load(file,function (){
///others code
})
}
</script>
</body>
</html>
a.html
This is A
<script>
//let x=10;
setInterval(() => {
//code for A
console.log("I am interval A 1st line")
console.log("I am interval A 2nd line")
}, 1000);
</script>
b.html
This is B
<script>
//let x=10;
setInterval(() => {
//code for B
console.log("I am interval B 1st line")
console.log("I am interval B 2nd line")
}, 1000);
</script>
Please Run the index.html,click the buttons and watch the console log.
2
Answers
Even though this may not be a straightforward answer to your question,but you may want to try if this works as a workaround.
and access it like this:
Method
.load()
immediately places loaded data in element. That is, you can’t do anything with the html before pasting.You can use
jQuery.get()
method and remove all<script>
tags before pasting. Something like this:DEMO