Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element, but keep all data and events bind

I have a container that could be injected in any specified container on the page (like a popup). Popup should have a button which deletes parent element. I tried using .remove() to delete parent element, however, it also removes popup and its events. I want it to remove popup (I still have the reference), however, I don't want .remove to unbind the events.

So far, I got this:

var popup = $('#popup');

$('body > div').on('click', function () {
    popup.appendTo($(this));
});

popup.find('button').on('click', function () {
    $(this).closest('div:not(#popup)').remove();
});

http://jsfiddle.net/volter9/0zms29g1/

Basically, is there a way to delete an element without removing its data or events?

Thank you for attention!

P.S.: I tried to append and hide popup in the body, but it's not what I need.

like image 760
volter9 Avatar asked Nov 03 '14 18:11

volter9


1 Answers

You can use .detach()

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Also you can append the detach element to the DOM by using the return value:

var div = $("div").detach();

$(div).appendTo("body");
like image 191
Alex Char Avatar answered Oct 16 '22 17:10

Alex Char