I’m working on a web page where I’m making an AJAX call that returns a chunk of HTML like:
<div> <!-- some html --> <script type='text/javascript'> /** some javascript */ </script> </div>
I’m inserting the whole thing into the DOM, but the JavaScript isn’t being run. Is there a way to run it?
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?
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:
<html> <head> <script type='text/javascript'> function addScript() { var str = "<script>alert('i am here');<\/script>"; var newdiv = document.createElement('div'); newdiv.innerHTML = str; document.getElementById('target').appendChild(newdiv); } </script> </head> <body> <input type="button" value="add script" onclick="addScript()"/> <div>hello world</div> <div id="target"></div> </body> </html>