I encountered an issue using jQuery's .delegate() method on IE8 when removing the elements to which my delegate handler was attached. Here's the scenario: I had a table with rows that each had a delete button. The rows were created dynamically, so the delete button was wired up using delegate to handle the click events. When it came time to remove the last row, the entire table was removed (table was only created once there was a value to create at least one row.) This worked fine just about everywhere with the one exception of IE8. Even then, it worked on some pages, but just not one (the exact same code was used on each page.) For this one particular page, deleting that last row would generate a js error in IE8 stating "Object required" - the offending line being in the jQuery code for delegate.
So the question is, what's the best practice with handlers when some of the DOM elements those handlers are using are removed? Should undelegate be called at some point, and if so, where?
Use jQuery's .remove()
method:
"Use
.remove()
when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed."
Or the .empty()
method to remove all children but keep the top level element.