Search code examples
jqueryclonehiddenelement

Copy a hidden element with clone() - better way?


I've managed to copy a hidden element ($("#products-area").find(".mysets-area")) by checking the state of the element, temporarily showing it and then hide it again after cloning.

But I may think there would be a better to achieve this?

var stateVisible = $("#products-area").find(".mysets-area").css("display");
if (stateVisible == 'none') {
    $("#products-area").find(".mysets-area").show();
}

$("#user-dialog .open-mysets").html($("#products-area").find(".mysets-area").clone());                

if (stateVisible == 'none') {
    $("#products-area").find(".mysets-area").hide();
}

Solution

  • Why not clone the element while it's hidden and show the new element?

    var orig = $("#products-area").find(".mysets-area");
    var cloned = $(orig).clone().show();
    $("#user-dialog .open-mysets").html(cloned);
    

    Shown in this JS Fiddle: http://jsfiddle.net/jaypeagi/qCwJA/2/