Tuesday, September 7, 2010

Web Dev Bug - Events on dynamically created elements in IE don't work


This bug has haunted me for some time. I found the solution awhile ago, but thought I'd share the solution since it didn't seem well documented online so I thought I'd throw it out there. When you create an element dynamically with javascript in IE, and try to put an even on it... ex.. onclick.., it simply won't work in IE.


The solution to this seems to be refreshing the HTML of that element. You can do this using the IE property outerHTML.


So say we created a new button with the id "newBtn", we could do something like this....


document.getElementById("newBtn").outerHTML = document.getElementById("newBtn").outerHTML


and presto, our events will work. If there is a more elegant solution to this problem in IE, I'm all ears, but for the time being this slightly hacky solution is pretty easy to implement.

No comments:

Post a Comment