Search code examples
javascriptjqueryhtmlhtml-manipulation

How can I "reset" <div> to its original state after it has been modified by JavaScript?


I have a DIV with a form in it. When users submit the form and it gets successfully submitted, I replace the form with a simple "everything is good now" message:

$("#some_div").html("Yeah all good mate!");

Is there a good way to "reset" the div to its "original state" as per the HTML it has arrived with? I can only think of actually doing something like this:

//before I change the DIV
var originalState = $("#some_div").html();
//manipulate the DIV
//...
//push the state back
$("#some_div").html(originalState);

It doesn't look very elegant - I guess there is a better solution for this, no?


Solution

  • 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