2014-02-04

IE problems with innerHTML

When writing a Javascript widget library, there is the constant need to test in all browsers. There are times like today that I just have to facepalm because of my findings.

One of the widgets I'm working with needs to have a button pushed inside of generated HTML. Because the button has event handlers, it was thought to just append the element inside the generated HTML.

In most browsers, this works. But in Internet Explorer, it appears that innerHTML wipes the contents of the element you're trying to append. In the following example, the button ends up being empty after setting the subsequent time.



The quick fix is to remove the child elements before calling innerHTML. Example shown below. Notice the lines that remove the child elements of the outer Element. This needs to be done first before calling innerHTML.



From what I can tell, IE must be doing something screwy with clearing content depth first when you set the innerHTML on an element. This makes it remove the contents of Elements you still have a reference to and are planning on reattaching to the DOM at a later time. To be safe, you should always remove the elements you want to reuse.

No comments: