Manipulating innerHtml disables event handlers set with JavaScript

If you manipulate innerHtml property of an HTML element with children and you've previously set any event handlers on those children with JavaScript (not with onxxxx attributes), they're gone (as the changing of innerHTML effectively erases all the children and recreates them). If you want to retain children event handlers, you should add new children with DOM calls (node.appendChild).

For example, if you set up onclick handler like this:
<div id="outerDiv">
<p id="para1">Click here</p>
</div>
<script>
var x = document.getElementById("para1");
x.onclick = function () { alert("Clicked"); }
</script>

... the onclick handler will stop working if you change innerHtml of outerDiv, for example to add another paragraph:
<script>
var outerDiv = document.getElementById("outerDiv") ;
outerDiv.innerHtml += "<p id='para2'>Another paragraph</p>" ;
</script>

No comments:

Post a Comment