How do you execute a dynamically loaded JavaScript block?

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>

Leave a Comment