I would like to modify a DOM subtree and restore it after a while. How can I save a sub-tree copy aside (to play with the actual subtree)? How can I restore the saved copy afterwards?
4 Answers
If I'm reading this right, then I think all you'd need to do is:
var DomTreeCopy = $('parentElementSelector').clone(true,true);
And then to re-attach the DomTreeCopy
(in place of the original):
$('parentElementSelector').replaceWith(DomTreeCopy);
Or to add it to the DOM in addition to the original:
$(DomTreeCopy).insertAfter($('parentElementSelector'));
References:

- 249,100
- 51
- 377
- 410
-
Thanks. Sharing an upvote, not marking as a perfect answer, since cloning won't support CSS styles/event handlers? Am I right, please? – BreakPhreak Jan 02 '12 at 17:00
-
1Did you read the reference material for `clone()`? The first `true, true` arguments passed to the method means that it copies data and events bound to the elements. The first `true` applies to the element cloned, and the second `true` to the children of the cloned element. As long as your stylesheet supports selectors matched by the elements cloned then yes, CSS will apply itself/be applied automatically. – David Thomas Jan 02 '12 at 17:04
-
brilliant, saved me a ton of time managing state of a custom (editable) control. – earthling Jul 09 '12 at 20:28
Using simple JavaScript:
var elem = document.getElementById('theElement'),
backupElem = elem.cloneNode(true);
// Your tinkering with the original
elem.parentNode.replaceChild(backupElem, elem);
Note that using this method, your event handlers are not restored. But you can back them up too, since they're just ordinary functions.
Turns out, I was wrong about that. The event handlers are preserved since it's the original DOM that you're restoring. If you were copying it and appending it elsewhere, the event handlers wouldn't be copied. This demo shows that the event handler remains.

- 15,854
- 10
- 58
- 67
you can use $.data()
... method
$.data(document.body, "sortElement", "0"); //set value
$.data(document.body, "sortElement"); //read value
this was you can store all waht you want in a dictionary type - and then reuse it later.

- 144,742
- 138
- 468
- 792
You can store the cloned object somewhere else in the DOM. Modify the DOM which is visible. When you require the actual value you can track it from the place where you have appended.
<div id="oldInfo"></div>
$("#youActualDom").clone().appendTo("#oldInfo").hide();
Then track the original dom with $("#oldInfo")

- 10,475
- 16
- 52
- 80