user663381
user663381

Reputation:

jQuery detach content with events?

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/

Upvotes: 1

Views: 1442

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263057

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();

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Try cloning the child elements, removing them and then adding them back using the clone.

var detachedContent = $(container).children().clone(true);
console.log(detachedContent);
container.empty();

container.append(detachedContent);

Working Example: http://jsfiddle.net/sCJfc/2/

Upvotes: 0

Related Questions