Monday, 3 December 2012

Remove Elements Without Deleting Data in jquery



The new ".detach()" method allows you to remove elements from the DOM, much like the ".remove()" method. The key difference with this new method is that it doesn’t destroy the data held by jQuery on that element. This includes data added via ".data()" and any event handlers added via jQuery’s event system.

This can be useful when you need to remove an element from the DOM, but you know you’ll need to add it back at a later stage. Its event handlers and any other data will persist.




var foo = jQuery('#foo'); 
// Bind an important event handler 
foo.click(function(){ 
    alert('Foo!'); 
}); 
foo.detach(); // Remove it from the DOM 
// … do stuff 
foo.appendTo('body'); // Add it back to the DOM 
foo.click(); // alerts "Foo!"

No comments:

Post a Comment