0

I can understand the purpose of clone() method when appending a copy element like this:

$aObject = $('.className').clone();
$aObject.removeAttr('id');
$('#add-line').click(function() {
   $('#container').append( $aObject.clone());
});

But what I don't understand is, if I get rid of the clone method, just using

$('#container').append( $aObject);

I should still be able to add multiple same object to the container, but it seems like I can only add the aObject once? can't we add same object many times on purpose just like an array of same objects?

3
  • Are you doing this inside of a function? If not, are you implicitly declaring $aObject? Commented May 13, 2018 at 14:43
  • 3
    If you call .append() on an existing object, it acts as a move. Commented May 13, 2018 at 14:44
  • stackoverflow.com/questions/25939472/… Commented May 13, 2018 at 14:51

1 Answer 1

0

When you assign an object to a variable in JavaScript, you aren’t actually assigning the object value stored in memory – rather a reference that points to the object’s location in memory.

So, when you declare $aObject, you have now stored a reference to a particular object. When you append it, it behaves as you would expect, appending the object that you are referencing. When you try to do the same thing again, it is referring to the same object that now already exists in the DOM and simply takes that object and re-appends it (what Scott Marcus meant when he said it acts as move).

If you clone it first, then you are referencing an entirely different object, which can be appended in addition to any objects you've already appended.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. But why jQuery doesn't allow append same object multiple times?
As I said in the comments, .append() on an existing item causes a move. If you want to append a new item, you need to make a copy first and append the copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.