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

二次信任 提交于 2019-11-26 16:01:54
Josiah Ruddell

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
Vadim

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'));

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.

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.

Somewhat more elegant?

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

In my opinion best is to use this:

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

This way you can repeatedly use this to restore your div to original state while keeping the data in "originalState" intact. Worked for me.

You have basically three options.

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

Making call to empty function in jQuery will do it

$(".div").empty();

This is my very first interaction on this site--I can't comment yet, but this is to @Fleuv's comment on @Josiah Ruddell's answer:

The default parameter for .clone() is "false", which will not clone event listeners. If you make it .clone(true) it clones the event listeners as well. I've tested it (with the rest of his answer) and it works.

w3schools jQuery clone() method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!