Reputation: 145
If you click option 2, it appends the original clone from page load but it wont repeat every time the button is clicked.
<a href="#" class="modify">1. Turn the element red...</a><br />
<a href="#" class="copy">2. Append the original black element...</a><br /><br />
<div id="container">
<div class="element">This is an element!</div>
</div>
$(document).ready(function () {
var obj = $(".element").clone(true);
$(".copy").click(function (e) {
e.preventDefault();
//alert(obj); //Just to see if it still exists.
$("#container").append(obj);
});
$(".modify").click(function (e) {
e.preventDefault();
$(".element").css("color", "#F00");
});
});
Here is my CodePen link http://codepen.io/anon/pen/dsvLm
Any ideas?
Upvotes: 1
Views: 987
Reputation: 82241
You need to create the clone while appending.Use:
var obj = $(".element");
$(".copy").click(function (e) {
e.preventDefault();
//alert(obj); //Just to see if it still exists.
$("#container").append(obj.clone(true));
});
Upvotes: 0
Reputation: 93571
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).
Instead just make a new clone of your disconnected cloned object (in its original state) each time you need one:
$("#container").append(obj.clone(true));
Upvotes: 3