I have two <div> elements, and the following JavaScript code:
var myObject = {
$input: $('<input />'),
insert: function () {
$('div').append(this.$input);
$('div').append(' ');
}
};
myObject.insert();
This, as I expect, produces an <input> element within each of the two <div> elements.
Now when I create a new instance of myObject and call insert() again I will be expecting 4 <input> elements, two in each <div>. Weirdly, I only get 3 <input> elements!
See example code here:
http://jsfiddle.net/FNEax/
You’re creating 1 input explicitly:
…but cloning it implicitly when you try to append it to multiple divs
Then
Object.createdoesn’t create a new$input, so on the second pass, it appends (moves) the input from the seconddiv(which is actually the original) to the firstdiv, and then does the implicit clone to populate the second.Here’s a jsFiddle example that increments an
ivariable wheneverinsert()is called, and adds it as the value of the input. Notice that it is always set at0.I also modified it to pass a string to
insertso you can see which call each input came from.The two inputs from the second call both still have the string passed to the first call.
EDIT:
I flipped it around mid explanation, but the concept is the same.
When the second
insert()is called, the clone is first created of the original and added to the firstdiv, then the original is appended to the seconddiv(where it already is).jQuery makes the clones first, then appends the original last.
Here’s another jsFiddle example that adds a custom property to the original, then adds some text next to the element with that custom property after each
insert(). The text is always added next to that original in the seconddiv.