I would like to reset the DOM to original state and then manipulate it again.
I have found that the best way to do this is as follows:
// Clone the Dom and assign it to a variable
divClone = $("#document").clone();
// .... More Code ......
// When required, replace the DOM with with the cloned variable.
$("#document").replaceWith(divClone);
The only problem is that you cannot manipulate the newly reseted DOM again.
I have put together a JSFiddle which uses a simple example of adding a class. You can click on the "test" link to add a a class. You can then click on "Reset" to return the DOM back to its original state. However, if you click on the "test" link again, no more classes will be added to the restored DOM. (Obviously, this is just a simplified example. There are better ways of removing and adding classes).
How can I manipulate the restored DOM?
Your code works as expected, the problem is the DOM you cloned does not have handlers bound to it.
You have 2 options, first one is to clone after all the handlers are bound, passing true
to the withDataAndEvents
clone
method argument:
$(".test").click(function() {
$("#document").addClass("green");
});
$(".reset").click(function() {
$("#document").replaceWith(divClone.clone(true));
});
var divClone = $("#document").clone(true);
Fiddle
The 2nd option is to use event delegation.
var divClone = $("#document").clone();
$(document).on('click', '.test', function() {
$("#document").addClass("green");
}).on('click', '.reset', function() {
$("#document").replaceWith(divClone.clone());
});
Fiddle
The drawback to this second approach is that all events have to bubble up to the document level and you can't cancel the bubbling with event.stopPropagation()
then.
Edit: Updated answer to replace with a clone of the clone, so that the original clone always stays safe at initial state and can serve as base for later resets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With