Search code examples
jqueryclone

Remove doesn't work in cloned object


Remove objects in this code works fine in jquery 1.5, but doesn't work with jquery 1.6:

<!DOCTYPE html>
<html>
<head>
<style>.content {border: 1px solid #333;} .delete {color: red;}</style>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
<div id="master">
<div class="content">Some content <span class="delete">Delete</span></div>
</div>
<div class="clone">Clone</div>
<script>
    $(".clone").click(function () {
        $("#master").find(".content").last().clone().appendTo("#master");
    });

    $(".delete").click(function () {
        $(this).parents(".content").remove();
    });
</script>
</body>
</html>

With Jquery 1.6+ I can remove just first element. Why it doesn't work?


Solution

  • There seems to be an issue with clone() in 1.5.0 that was fixed in 1.5.1 regarding the optional withDataAndEvents parameter.

    From the documentation:

    In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.

    Your code should thus be:

    $(".clone").click(function () {
        $("#master").find(".content").last().clone(true).appendTo("#master");
    });
    
    $(".delete").click(function () {
        $(this).parents(".content").remove();
    });