My question is, why isn't the click event on the third div triggered anymore, after i've detached the elements and appended them back? The events aren't preserved.
var test = (function($, undef) {
var t = {};
t.test = function(){
var container = $('<div/>').appendTo('body');
$('<div/>', {
'class' : 'some',
'text' : 'text'
}).appendTo(container);
$('<div/>', {
'class' : 'some',
'text' : 'text'
}).appendTo(container);
$('<div/>', {
'class' : 'some',
'text' : 'text',
'click' : function(){
console.log("ahoy");
}
}).appendTo(container);
$('<div/>', {
'class' : 'some',
'text' : 'text'
}).appendTo(container);
var content = container.html();
var detachedContent = $(content).detach();
container.empty();
//setTimeout(function(){
container.append(detachedContent);
//}, 2000);
};
return t;
})(jQuery);
test.test();
example: http://jsfiddle.net/sCJfc/
detach() is not to blame here.
You're performing a copy of the container element's inner markup, and you're detaching the elements created from that copy. These elements are not part of the DOM to begin with, and will indeed not have any handler registered on them.
Try writing:
var detachedContent = container.children().detach();
Instead of:
var content = container.html();
var detachedContent = $(content).detach();