I have a div in my HTML page:
<div id="dynamicScript"></div>
I generate a dynamic JS code on a textbox blur operation:
var dynamicScriptText = `$(document).on('click','#${id}',function(){alert();});`;
Now, I have created a script using JS. But I am deleting the script first if it already exists and then regenerate it with an dynamic id and appending it to my dynamicScript DIV:
var id = "ControlTool10706547031";
var elem = document.getElementById("script" + id);
if(elem){
elem.parentNode.removeChild(elem);
}
var script;
script = document.createElement('script');
script.type = 'text/javascript';
script.id = "script" + id;
script.innerHTML = dynamicScriptText;
var dynSc = document.getElementById('dynamicScript');
dynSc.appendChild(script);
This code generates following output when I inspect element in Chrome DevTools:
<div id="dynamicScript">
<script type="text/javascript" id="scriptControlTool10706547031">
$(document).on('click','#ControlTool10706547031',function(){alert();});
</script>
</div>
Here, #ControlTool10706547031 is a button and on click of it I am trying to show an alert.
But the problem is, on textbox blur, although I am deleting the script each time by the following code before re-appending it:
var elem = document.getElementById("script" + id);
if(elem){
elem.parentNode.removeChild(elem);
}
it is somehow caching the generated JS code and suppose if I run my textbox blur operation 5 times, when I click my button #ControlTool10706547031 the alert message is coming 5 times although when I inspect element in Chrome DevTools:
<div id="dynamicScript">
<script type="text/javascript" id="scriptControlTool10706547031">
$(document).on('click','#ControlTool10706547031',function(){alert();});
</script>
</div>
This code is showing once.