How to clone (and restore) a DOM subtree

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?

Answers:

Answer

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:

Answer

Using simple JavaScript:

var elem = document.getElementById('theElement'),
    backupElem = elem.cloneNode(true);
// Your tinkering with the original
elem.parentNode.replaceChild(backupElem, elem);

Working demo

MDN - cloneNode

MDN - replaceChild

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.

Answer

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.

http://api.jquery.com/jQuery.data/

Answer

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")

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.