Why do logged events disappear when an item is removed from the DOM?

This jQuery 1.3.2 code adds an element to the page, logs a click event, and then removes and re-binds the element:

var button = $('<button>Click me!</button>') .click(function(){ alert("Hello") }) .appendTo('body'); $('body').html(''); button.appendTo('body'); 

The button appears on the page as expected, but clicking on it does nothing. I would like to know why the event handlers were removed from the object.

Note. I know solutions like jQuery.live() or clone(true) , or using appendTo without deleting. What I'm looking for is an explanation, not a solution or a workaround.

EDIT: I guess this could be an arbitrary and inconsistent DOM design decision. An explanation like "Because the way section X of specification Y wants it to be" will be fine.

+6
javascript jquery dom javascript-events
source share
2 answers

When you delete an element from the DOM using jQuery, all data (including event handlers) stored by jQuery in that element will be destroyed. This is to prevent memory leaks.

This is not a function (or error) of the DOM API. This is just jQuery.

+6
source share

If you want your logged events to remain on your element, use .detach () instead of .remove (). Use it the same way you use .remove (), it will contain your events in your element.

+5
source share

All Articles