AidOnline01
AidOnline01

Reputation: 737

Don't lose variable data when removing element

How can I save elements to variable, then remove it, but not lose the variable data?

var elements = $('.element');
elements.remove();
elements.insertAfter('.insertAfterElement');

Upvotes: 2

Views: 102

Answers (3)

Oriol
Oriol

Reputation: 288080

From http://api.jquery.com/remove/:

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

From http://api.jquery.com/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.

But of course, if you are going to insert it back to the document immediately, there is no point in using that.

$('button').on('click', function() {
  $('.element').insertAfter('.insertAfterElement');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Wrapper <span class="element">Element</span></div>
<button>Click me</button>
<div class="insertAfterElement"></div>

Upvotes: 1

Bergi
Bergi

Reputation: 664395

From http://api.jquery.com/remove/:

To remove the elements without removing data and events, use .detach() instead.

So you'd use

var elements = $('.element');
elements.detach();
// later:
elements.insertAfter('.insertAfterElement');

However, if you only want to move the elements around immediately, you don't need to explicitly remove them from the DOM at all. Just inserting them in a different position will implicitly remove them from their old position (instead of getting them cloned). So simply use

$('.element').insertAfter('.insertAfterElement');

Upvotes: 0

mx0
mx0

Reputation: 7113

Use .detach() instead of .remove().

From docs:

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.

Upvotes: 4

Related Questions