« Live.com Zillow Gadget for Tracking Your Home Value | Main | Building database and web service driven asynchronous google map application »

innerHTML could invalidate the event handlers of its child elements

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.

TrackBack

TrackBack URL for this entry:
http://stanblog.jojoyao.com/cgi-bin/mt/mt-tb.cgi/45

Post a comment


About

This page contains a single entry from the blog posted on May 10, 2007 9:48 PM.

The previous post in this blog was Live.com Zillow Gadget for Tracking Your Home Value.

The next post in this blog is Building database and web service driven asynchronous google map application.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33