I wanted to copy DOM element in variable, so I did this:
var before=$("#someid").html();
Then my script does a bunch of stuff in this "someid" DOM and after that is completed I restored DOM like it was before:
$("#someid").html(before);
This works ok but the problem is that I had some events in this DOM and those events can not be copied like this... So is there another way to do this?
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.
clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
Syntax: // Create a clone of the object using the extend() method let newObj = jQuery. extend({}, obj); // Create a deep clone of the object using the deep parameter let newDeepObj = jQuery. extend(true, {}, obj);
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
The clone() method can preserve both event handlers and element data. You can write:
var $before = $("#someid").clone(true);
Then later:
$("#someid").replaceWith($before);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With