<p>I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: </p>

<pre><code>&lt;div&gt;
  &lt;!-- some html --&gt;
  &lt;script type="text/javascript"&gt;
    /** some javascript */
  &lt;/script&gt;
&lt;/div&gt;
</code></pre>

<p>I'm inserting the whole thing into the DOM, but the JavaScript isn't being run.  Is there a way to run it?  </p>

<p>Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed.  I can't call eval on the response because the JavaScript is within a larger block of HTML.  I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky.  Anyone know a better way?</p>

[{'answer_id': 76003, 'author': 'Scott Nichols', 'author_id': 4299, 'author_profile': 'https://Stackoverflow.com/users/4299', 'pm_score': 4, 'selected': False, 'text': "<p>You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName. </p>\n\n<pre><code>div.innerHTML = response;\nvar scripts = div.getElementsByTagName('script');\nfor (var ix = 0; ix &lt; scripts.length; ix++) {\n    eval(scripts[ix].text);\n}\n</code></pre>\n"}, {'answer_id': 76054, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': 1, 'selected': False, 'text': '<p>The best method would probably be to identify and eval the contents of the script block directly via the DOM.</p>\n\n<p>I would be careful though.. if you are implementing this to overcome a limitation of some off site call you are opening up a security hole.</p>\n\n<p>Whatever you implement could be exploited for XSS.</p>\n'}, {'answer_id': 76068, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative is to not just dump the return from the Ajax call into the DOM using InnerHTML.</p>\n\n<p>You can insert each node dynamically, and then the script will run.</p>\n\n<p>Otherwise, the browser just assumes you are inserting a text node, and ignores the scripts.</p>\n\n<p>Using Eval is rather evil, because it requires another instance of the Javascript VM to be fired up and JIT the passed string.</p>\n'}, {'answer_id': 76100, 'author': 'Ed.', 'author_id': 12257, 'author_profile': 'https://Stackoverflow.com/users/12257', 'pm_score': 5, 'selected': True, 'text': "<p>Script added by setting the innerHTML property of an element doesn't get executed.  Try creating a new div, setting its innerHTML, then adding this new div to the DOM.  For example:</p>\n\n<pre>\n&lt;html&gt;\n&lt;head&gt;\n&lt;script type='text/javascript'&gt;\nfunction addScript()\n{\n    var str = &quot;&lt;script&gt;alert('i am here');&lt;\\/script&gt;&quot;;\n    var newdiv = document.createElement('div');\n    newdiv.innerHTML = str;\n    document.getElementById('target').appendChild(newdiv);\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;input type=&quot;button&quot; value=&quot;add script&quot; onclick=&quot;addScript()&quot;/&gt;\n&lt;div&gt;hello world&lt;/div&gt;\n&lt;div id=&quot;target&quot;&gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</pre>\n"}, {'answer_id': 76387, 'author': 'Diodeus - James MacFarlane', 'author_id': 12579, 'author_profile': 'https://Stackoverflow.com/users/12579', 'pm_score': 0, 'selected': False, 'text': '<p>You can use one of the popular Ajax libraries that do this for you natively. I like <a href="http://www.prototypejs.org/" rel="nofollow noreferrer">Prototype</a>. You can just add evalScripts:true as part of your Ajax call and it happens automagically.</p>\n'}, {'answer_id': 35462561, 'author': 'Roman Vottner', 'author_id': 1377895, 'author_profile': 'https://Stackoverflow.com/users/1377895', 'pm_score': 3, 'selected': False, 'text': '<p>While the accepted answer from @Ed. does not work on current versions of Firefox, Google Chrome or Safari browsers I managed to adept his example in order to invoke dynamically added scripts.</p>\n\n<p>The necessary changes are only in the way scripts are added to DOM. Instead of adding it as <code>innerHTML</code> the trick was to create a new script element and add the actual script content as <code>innerHTML</code> to the created element and then append the script element to the actual target.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script type=\'text/javascript\'&gt;\nfunction addScript()\n{\n    var newdiv = document.createElement(\'div\');\n\n    var p = document.createElement(\'p\');\n    p.innerHTML = "Dynamically added text";\n    newdiv.appendChild(p);\n\n    var script = document.createElement(\'script\');\n    script.innerHTML = "alert(\'i am here\');";\n    newdiv.appendChild(script);\n\n    document.getElementById(\'target\').appendChild(newdiv);\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;input type="button" value="add script" onclick="addScript()"/&gt;\n&lt;div&gt;hello world&lt;/div&gt;\n&lt;div id="target"&gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This works for me on Firefox 42, Google Chrome 48 and Safari 9.0.3</p>\n'}, {'answer_id': 63677480, 'author': 'Matthew Beck', 'author_id': 2413712, 'author_profile': 'https://Stackoverflow.com/users/2413712', 'pm_score': 0, 'selected': False, 'text': '<p>For those who like to live dangerously:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// This is the HTML with script element(s) we want to inject\nvar newHtml = \'&lt;b&gt;After!&lt;/b&gt;\\r\\n&lt;\' +\n  \'script&gt;\\r\\nchangeColorEverySecond();\\r\\n&lt;/\' +\n  \'script&gt;\';\n  \n// Here, we separate the script tags from the non-script HTML\nvar parts = separateScriptElementsFromHtml(newHtml);\n\nfunction separateScriptElementsFromHtml(fullHtmlString) {\n    var inner = [], outer = [], m;\n    while (m = /&lt;script&gt;([^&lt;]*)&lt;\\/script&gt;/gi.exec(fullHtmlString)) {\n        outer.push(fullHtmlString.substr(0, m.index));\n        inner.push(m[1]);\n        fullHtmlString = fullHtmlString.substr(m.index + m[0].length);\n    }\n    outer.push(fullHtmlString);\n    return {\n        html: outer.join(\'\\r\\n\'),\n        js: inner.join(\'\\r\\n\')\n    };\n}\n\n// In 2 seconds, inject the new HTML, and run the JS\nsetTimeout(function(){\n  document.getElementsByTagName(\'P\')[0].innerHTML = parts.html;\n  eval(parts.js);\n}, 2000);\n\n\n// This is the function inside the script tag\nfunction changeColorEverySecond() {\n  document.getElementsByTagName(\'p\')[0].style.color = getRandomColor();\n  setTimeout(changeColorEverySecond, 1000);\n}\n\n// Here is a fun fun function copied from:\n// https://stackoverflow.com/a/1484514/2413712\nfunction getRandomColor() {\n  var letters = \'0123456789ABCDEF\';\n  var color = \'#\';\n  for (var i = 0; i &lt; 6; i++) {\n    color += letters[Math.floor(Math.random() * 16)];\n  }\n  return color;\n}</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;Before&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}]
['https://Stackoverflow.com/questions/75943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4243/']