2

Background

I want to dynamically put some javascript code in a DIV element using innerHTML. For this, I create a DIV object on my page and two buttons. First button, when pressed should insert some javascript code in the DIV element and the other function should utilize that code to execute some instructions.

Effort 1

I begin with this approach:

<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
    var code="<script type='text/javascript'>\nfunction msgbox(msg){\nalert(msg);\n}\n</script>";
    function setcode(obj)   {
    obj.innerHTML=code;
    }
</script>
</head>
<body>
<div id="hello">
    &nbsp;
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("what up man?!");'>CHECK</button>
</body>
</html>

For reasons lame and unknown, I discover that using </script> in a javascript string immediately tends to close the <script> code, even when the thing is properly wrapped in quote marks.

Anyhow. I change the coding slightly so that </script> is formed by combining two strings and does not appear together.

Effort 2

<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
    var xo="</";
    var code="<script type=\"text/javascript\">\nfunction msgbox(msg){\nalert(msg);\n}\nmsgbox('aha!');\n"+xo+"script>";
    function setcode(obj)   {
    obj.innerHTML=code;
    }
</script>
</head>
<body>
<div id="hello">
    &nbsp;
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("what up man?!");'>CHECK</button>
</body>
</html>

The Problem

Even with the second effort, I still can't get the thing to work. After clicking the SET button, javascript code for defining msgbox() function should have been added to DIV's innerHTML and when CHECK button is pressed, that code should have worked and displayed a message on the screen.

But ... it does not.

WHYYYYYYYYYY???????!!!!!!!!

Youstay Igo
  • 321
  • 2
  • 11
  • Also: http://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml – Alexander O'Mara Nov 04 '15 at 07:34
  • 3
    BTW, you can avoid the `` issue by escaping the slash like this: `var script = ' – Alexander O'Mara Nov 04 '15 at 07:35
  • You're adding scripts the the DOM after you've added the buttons. The buttons cannot know those functions are to be added as they don't watch the DOM - therefore it errors - btw effort one, change `` to `<\/script>` and it works fine - for this to work your onclicks will have to be document finds – StudioTime Nov 04 '15 at 07:37
  • Thanks. Yes it's the same issue as you have linked to. I should refer to those questions instead. Thanks for pointing that out. You can close my question :) – Youstay Igo Nov 04 '15 at 07:37

0 Answers0