Question

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

elem1.parentNode.removeChild(elem1);
Was it helpful?

Solution

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.

OTHER TIPS

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.

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:

var stack = [];
function removeWithStack() {
    let elem = this,
        parent = elem.parentNode;

    // Note: index here is ES6 only; for ES5 see https://stackoverflow.com/a/23528539/2065702
    let action = {
        "index": Array.from(parent.children).indexOf(elem),
        "parent": parent,
        "elem": parent.removeChild(elem)
    }

    stack.push(action);
}

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

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

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

function popAddStack() {
	let 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>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top