Archive

Posts Tagged ‘dom’

innerHTML could invalidate the event handlers of its child elements

May 10th, 2007

In Javascript, using an element’s innerHTML property to dynamically edit its content provides much flexibility and convenience.  But special care needs to be taken when using it, because it could bite you silently.  Take one of my experiences as an example, it could break the event handlers of the child elements.  Sample code as the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>innerHTML</title>
</head>
<body>

<hr /><div id="myd"></div><hr />

<script language="javascript">
function myaction()
{
    alert("hello");
}

var d1 = document.createElement("div");
d1.onclick = myaction;
d1.innerHTML = "child div";

var d = document.getElementById("myd");
d.appendChild(d1);
//d.innerHTML += "parent div";
</script>

</body>
</html>

This code works well and when you click on div, "hello" will pop up.  However if you uncomment the last line of the JavaScript code.  The message won’t pop up any more.  innerHTML manipulates the content of the element as a string instead of DOM, so it might just break the underlying "wires" that hooks up the elements and their event handlers.  So watch out, when any of the events stops working as expected, look for the evil "innerHTML" first.

Web , ,