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?

1 Answers1

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.

ninjaAF
  • 524
  • 2
  • 5
  • thanks for the answer. But why jQuery doesn't allow append same object multiple times? –  May 14 '18 at 00:07
  • 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. – Scott Marcus May 14 '18 at 01:26