How to clone (and restore) a DOM subtree

前端 未结 4 2011
别那么骄傲
别那么骄傲 2021-01-04 04:30

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 a

4条回答
  •  灰色年华
    2021-01-04 05:08

    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.

提交回复
热议问题