I have a php file that echos an HTML with <script>
element. like this:
<div>
<button onclick="FunctionName();">Click Me</button>
</div>
<script type="text/javascript" id="script1">
function FunctionName() {
/* block of code here */
}
</script>
<script type="text/javascript" id="script2">
alert("working")
</script>
I'm inserting this code in via innerHTML method. However, I figured out that the DOM inserted <script>
tag doesn't get executed unless you call it like this:
eval(document.getElementById('script1').innerHTML);
eval(document.getElementById('script2').innerHTML);
Now the problem is: the script2 is executing and it is doing an alert that says: "working", but when I click the button the console returns this error:
Uncaught ReferenceError: FunctionName is not defined
And the weird part is when I copy/paste the same JavaScript Code, put it inside an eval(); and enter it in the console, it works perfectly!
so why is that happening and how to solve it?