Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 973
BreakPhreak Avatar asked Jan 02 '12 14:01

BreakPhreak


3 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:

  • clone().
  • insertAfter().
  • replaceWith().
like image 197
David Thomas Avatar answered Nov 10 '22 20:11

David Thomas


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.

like image 10
Some Guy Avatar answered Nov 10 '22 20:11

Some Guy


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/

like image 1
Royi Namir Avatar answered Nov 10 '22 20:11

Royi Namir