Use jQuery for Reset Dom and then process it again

I would like to reset the DOM to its original state, and then manipulate it again.

I found the best way to do this :

// 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 reset DOM again.

I have compiled a JSFiddle that uses a simple example of adding a class. You can click the test link to add a class. Then you can click "Reset" to return the DOM to its original state. However, if you click the test link again, no classes will be added for the restored DOM. (Obviously, this is just a simplified example. There are better ways to remove and add classes).

How can I manage the restored DOM?

+4
source share
1 answer

Your code works as expected, the problem is that the DOM you cloned does not have handlers associated with it.

You have 2 options, the first is to clone after all the handlers are bound by 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 second 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 disadvantage of this second approach is that all events must bubble up to the document level, and you cannot cancel the bubbling with event.stopPropagation() .


Edit: An updated response to replace a clone with a clone so that the original clone is always in a safe state in its original state and can serve as a basis for subsequent drops.

+4
source

Source: https://habr.com/ru/post/1445350/


All Articles