jQuery Appending an Object multiple times
It is because in the first case it is referring to the same element object (appends same element so it's appended to new place), and in second case you are appending html as string so it appends multiple elements (new element every time).
In the first case, $
will parse your html and create a new jQuery object which will wrap over an HTMLInputElement
.
Basically, it's like doing:
var $newDiv = $('#newDiv'),
newInput = document.createElement('input');
$newDiv.append(newInput);
$newDiv.append(newInput);
In the second case, it's parsing the html every time, generating a different jQuery object for every instance.
Here's how the first sample could be fixed:
var newInput = $('<input/>');
$('#newDiv').append(newInput);
$('#newDiv').append(newInput.clone());
When you do $('<input/>')
, jQuery creates an input
DOM element for you.
When you .append()
a DOM element, it detaches the element from its previous position. (See Fiddle). From the docs:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
Thus, your second .append()
call will remove it from where it was appended first and place it in the new position.
When you append a string, the DOM element is created as it is appended.