Rectangle 27 0

What you're doing is not optimal. The best solution would be this:

When the form gets successfully submitted, just hide() the FORM element, and show() the message (which is initially hidden). And then, later, just show() the FORM element and hide() the message.

Mmmm, how much more beneficial is this? I mean - why is this not optimal - how much is show/hide better?

@abolotnov Writing your FORM element into a string will destroy all event handlers that are bound on that form or any of its ancestor elements (like form fields). All other changes that were done programmatically on the form element or any ancestor will be lost too. HTML rewriting is a horrible idea.

@imeVidas what is your thought on using .clone(true, true) which will also clone data and event handlers, and will also do that for all children of the cloned element(as per jQuery API doc)?

concerning the use case the OP was facing, or as in you example, in case might you want to clone a FORM element.

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation
Rectangle 27 0

var originalState = $("#some_div").clone();
$("#some_div").replaceWith(originalState);

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation
Rectangle 27 0

You have basically three options.

  • Remember your original markup, as you do with your originalState variable above.
  • Use AJAX to re-request the markup. You can do this easily if you have server side code using the $.ajax() method in jQuery.

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation
Rectangle 27 0

You can use the data attribute to save the state rather than a variable

$('#some_div').data('old-state', $('#some_div').html());
$('#some_div').html($('#some_div').data('old-state'));

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation
Rectangle 27 0

I would clone the element, instead of saving the content. Then use replaceWith to restore it:

var divClone = $("#some_div").clone(); // Do this on $(document).ready(function() { ... })

$("#some_div").html("Yeah all good mate!"); // Change the content temporarily

// Use this command if you want to keep divClone as a copy of "#some_div"
$("#some_div").replaceWith(divClone.clone()); // Restore element with a copy of divClone

// Any changes to "#some_div" after this point will affect the value of divClone
$("#some_div").replaceWith(divClone); // Restore element with divClone itself

did not knew about replaceWith, very nice!

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation
Rectangle 27 0

Yeah, the way you have is the way to do it. The DOM does not save the previous states of DIVs, so you need to save that yourself.

jquery - How can I "reset"
to its original state after it has be...

javascript jquery html manipulation