How to Restore an Element Removed with jQuery?

17,746

Solution 1

You can't get that particular instance back. Using $.remove() removes it from the DOM. You can create a clone of it, move it around the DOM, hide it, etc., though. Depending on what your project requires, you likely have many other options.

If you're not too interested in that particular instance, you can create a new one. Suppose that was a div with a statement:

$("<div />").addClass("notification").text("I exist!").appendTo("body");

If you want to keep a copy of that particular element around, you can $.clone() it and remove the original:

var clone = $(".notification").clone(); // making zeh' clones!
$(".notification").remove();            // original is gone
$("body").append(clone);                // appears to have returned

Solution 2

Check out the jQuery 1.4 method .detach(). It lets you "remove" elements from the DOM and saves them so they can be reinserted later.

Solution 3

detach() does what remove() does, with the difference that remove will also take out any event handlers on the element. So long as a reference is made at some point, an element can be removed or detached equally, and be returned to the DOM

noti = $('.notification').remove();
$('body').append( noti ); // later
Share:
17,746
Hulk
Author by

Hulk

Updated on June 09, 2022

Comments

  • Hulk
    Hulk almost 2 years

    if an element is removed using

    $('.notification').remove();
    

    How do we create it back.