Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .data lost after remove() and append()

Sorry, this seems like a stupid question... but is this actually expected behaviour?

I store data on some element:

$('#source-list li.active').data('relation-text', textEditor.value());

Later the element is moved from one list to another:

$('#source-list li.active').remove().appendTo('#target-list')

Right before 'remove()' 'data()' returns the expected value. After remove(), the data is gone.

I would know how to work around this... but it seems odd to me - is this expected behavior?

like image 681
Wolfgang Avatar asked Aug 04 '14 14:08

Wolfgang


2 Answers

I think, so, judging from the Jquery Documentation:

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

Ergo, even though you can still reference it, because the DOM element has been removed, the data associated with it has been removed.

like image 79
Joeppie Avatar answered Sep 20 '22 03:09

Joeppie


You can use .detach() according to JQuery:

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.

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

$(div).appendTo("body");
like image 41
Zoki Avatar answered Sep 21 '22 03:09

Zoki