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!
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 anHTMLInputElement
.Basically, it's like doing:
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:
When you do
$('<input/>')
, jQuery creates aninput
DOM element for you.When you
.append()
a DOM element, it detaches the element from its previous position. (See Fiddle). From the docs: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.