Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy DOM element with its events in variable (jQuery)

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?

like image 381
domagojk Avatar asked Apr 25 '11 12:04

domagojk


People also ask

How do I grab an element from a dom?

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.

When using clone () which attribute can create conflict?

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.

How do you clone an object in jQuery?

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

How do you clone an element in Javascript?

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.


1 Answers

The clone() method can preserve both event handlers and element data. You can write:

var $before = $("#someid").clone(true);

Then later:

$("#someid").replaceWith($before);
like image 178
Frédéric Hamidi Avatar answered Sep 21 '22 03:09

Frédéric Hamidi