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"> var d1 = document.createElement("div"); var d = document.getElementById("myd"); </body> |
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.