0

Do you know how I could recover an item deleted with JavaScript in the following way:

elem1.parentNode.removeChild(elem1);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ivan
  • 35
  • 1
  • 8

3 Answers3

3

As written in the MDN documentation removeChild will return a reference to the removed child node. Usage like this:

var oldChild = element.removeChild(child);
element.removeChild(child);

Further:

The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.

m90
  • 11,434
  • 13
  • 62
  • 112
2

Without storing the element in a variable prior to deleting it, you can't undo a removeChild() call. Calling the function on its own without an assignment will completely remove it from the DOM and memory.

You can force JavaScript to store it in memory for use / restoration later by doing this:

var restoration_element = elem1.parentNode.removeChild(elem1);

Using the latter syntax with an assignment operator will remove the element elem1 from the display list, but keep it as a reference for use later.

BenM
  • 52,573
  • 26
  • 113
  • 168
1

I needed to not only get a reference for the deleted node, but also insert the deleted node back to the same location it was deleted from. As such, I had to use a stack like so:

// Note: This is ES6; for ES5 see https://stackoverflow.com/a/23528539/2065702
const stack = [];
function removeWithStack() {
    const elem = this,
          parent = elem.parentNode;
    
    const action = {
        "index": Array.from(parent.children).indexOf(elem),
        "parent": parent,
        "elem": parent.removeChild(elem)
    }
    
    stack.push(action);
}

function popAddStack() {
    const action = stack.pop();
    action.parent.insertBefore(action.elem, action.parent.children[action.index]);
}

const ps = document.querySelectorAll("p");

// Note: This is ES6; for ES5 see https://stackoverflow.com/a/23528539/2065702
const stack = [];
function removeWithStack() {
    const elem = this,
          parent = elem.parentNode;

    const action = {
        "index": Array.from(parent.children).indexOf(elem),
        "parent": parent,
        "elem": parent.removeChild(elem)
    }

    stack.push(action);
}

function popAddStack() {
    const action = stack.pop();
    action.parent.insertBefore(action.elem, action.parent.children[action.index]);
}

document.querySelector("button").onclick = popAddStack;

ps.forEach(function(p) {
    p.onclick = removeWithStack;
});
button,
p {
    cursor: pointer;
}
<div>
    <p>Test 1</p>
    <p>Test 2</p>
    <p>Test 3</p>
    <p>Test 4</p>
    <p>Test 5</p>
</div>
<button>Undo</button>
Zach Saucier
  • 24,871
  • 12
  • 85
  • 147