I am not sure what exactly is happening here, I think the fact that the variable is a jquery object.
This only appends once, my question is why?
var newInput = $('<input/>');
$('#newDiv').append(newInput);
$('#newDiv').append(newInput);
Though this works as I would assume
var newInput = '<input>';
$('#newDiv').append(newInput);
$('#newDiv').append(newInput);
Thank you for your help!
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With