I have a javascript variable:
var foo='<script type="text/javascript">alert("Hello World");<\/script>'
The variable is inserted with element.innerHTML=foo; after an event occurs on the page, about 10 seconds after the page is loaded.
Is there a way to execute the ‘alert’ function right after the insertion?
If you absolutely, positively have to take JavaScript code that’s in a string and execute it, you basically have to use
evalor aneval-like mechanism. In some years of JavaScript programming, I’ve never had to resort to it, and I do suggest that you look at whether there’s another way to achieve your actual overall goal.So here, you’d strip off the script tag stuff and just
evalthe code, e.g.:Obviously you have to be sure you trust the source of the string, since you’re executing the code therein.
evalis a slippery beast and plays very odd games with context and scope. If you need something that looks more like what you’d get if you did add a script tag to the page, here’s a function that does that cross-browser (from my answer to this other question here on Stack Overflow):Live example using the above