Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jquery to Reset the Dom and then manipulate it again

Tags:

jquery

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?

like image 897
big_smile Avatar asked Nov 11 '12 16:11

big_smile


1 Answers

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.

like image 77
Fabrício Matté Avatar answered Oct 06 '22 20:10

Fabrício Matté