lewis2z
lewis2z

Reputation: 145

jQuery won't append a clone declared at document ready

My issue is that if I create a clone variable on page load, jQuery will only append it once. Weird!

<p>Click to copy</p>
<div id="container">
    <div class="element">This is an element!</div>
</div>
$(document).ready(function () {
    var obj = $(".element").clone(true);
    $("p").click(function () {
        //alert(obj); //Just to see if the variable is still an object.
        $("#container").append(obj);
    });
});

Here is my CodePen link http://codepen.io/anon/pen/Fwduf

This is what I'm getting after 5 clicks:

Click to copy

This is an element!
This is an element!

What I should be seeing:

Click to copy

This is an element!
This is an element!
This is an element!
This is an element!
This is an element!
This is an element!

Interestingly, if I move the variable deceleration inside the click event, the append works completely as expected.

Upvotes: 2

Views: 699

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to clone it every time

Codepen Demo

$(document).ready(function () {
    var obj = $(".element");
    $("p").click(function () {
        //alert(obj); //Just to see if the variable is still an object.
        $("#container").append(obj.clone(true));
    });
});

In your case you are creating a new cloned element only once, after that you are just moving the existing element from one place to another

Upvotes: 4

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Arun's answer is correct but does not explain why you need to clone your template element each time you want a new element.

One feature of an individual DOM element, that you may not have been aware of, is that it can only have one parent. This makes sense as the DOM tree connects elements up, down, and sideways to each other and only have a single parent-element link (and a single next and single prev sibling element link) but a list of multiple children.

When you clone an element, you create a new DOM element that is effectively a new branch in a DOM tree (if only a small one). Calling append adds the element to its new parent, but it also points a parent link of your clone to its new parent. By appending the same element over and over you are simply changing the parent of a single element (i.e. moving it in the DOM tree).

As the interaction only runs at user interface speed (i.e. mouse click), you might as well simplify your code to:

$("p").click(function () {
    $("#container").append($(".element:first").clone(true));
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/7h8MK/1/

Upvotes: 1

Related Questions