binaryorganic
binaryorganic

Reputation: 1594

How to I undo .detach()?

I'm using JQuery 1.5 and the following code to detach li elements w/ a certain class when a button is clicked. What I want to know is, when that button is clicked again, how do I add the element back onto the page?

    <script>
    $("#remove").click(function () {
      $('li.type').fadeOut(300, function() { $(this).detach(); });
    });</script>

Upvotes: 5

Views: 3250

Answers (2)

Hitesh Prajapati
Hitesh Prajapati

Reputation: 2852

here u can't for loop.

var demo;
$('li.type').fadeOut(300, function() {
     demo = $(this).detach();
});

$('#replace').click(function() {
   $("ul#foo").append(demo);
});

Upvotes: 1

VoteyDisciple
VoteyDisciple

Reputation: 37813

The question is: where on the page do you want to put the element back? If, for example, all the li elements go back inside <ul id="foo"></ul> you might use something like this:

var items = [];
$('li.type').fadeOut(300, function() {
     items.push( $(this).detach() );
});

$('#replace').click(function() {
    for(var i = 0; i < items.length; i++) {
        $("ul#foo").append(items[i]);
    }
    items = [];
});

Upvotes: 7

Related Questions