Skip to content Skip to sidebar Skip to footer

Maintain Reference In Jquery.clone() Element To Original Element

I was surpised to see the jQuery did not include any functionality in the resulting element of a $.clone() operation to recall the source element. My work-around was to simply incl

Solution 1:

Edit, Updated

jQuery's prevObject property appear to save reference to original object

Try (v3)

var$elOriginal = $("div");
var$elClone = $("div").clone(true, true);
$elClone.html(123);
$("body").append($elClone);
console.log($elClone.prevObject.html())

var $elOriginal = $("div");
    var $elClone = $("div").clone(true, true);
    $elClone.html(123);
    $("body").append($elClone);
    console.log($elClone.prevObject.html())
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div>abc</div>

Solution 2:

Use withDataandEvents and deepWithDataAndEvents to copy the events and data for the element and all children of the cloned element.

$elClone.clone(true, true);

From the docs -

Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy. As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

Post a Comment for "Maintain Reference In Jquery.clone() Element To Original Element"