18

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!

VIDesignz
  • 4,703
  • 3
  • 25
  • 37

5 Answers5

24

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());
plalx
  • 42,889
  • 6
  • 74
  • 90
21

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.

Cem Schemel
  • 442
  • 3
  • 13
Stryner
  • 7,288
  • 3
  • 18
  • 18
1

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).

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

You can append multiple elements by creating new element each time with loop:

(function(){
  for(var i=0; i<10; i++){
    var newInput = $('<input>');
    $('#newDiv').append(newInput);
}})();
input {border:1px solid red; margin:3px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newDiv"></div>
OPTIMUS PRIME
  • 1,297
  • 9
  • 20
1

The append method actually moves the element so, if you check this code in debugger with different div tags you will see the element will be created once and then moved to next div in your case it is being moved to same div. To solve this you can use the clone method in to create a new clone of the element every time you append it.

example HTML :

<div id="hello">
  
</div>

JS :

function addToDiv(div,data){
  $('#'+div).append(data)
}

$(document).ready(function() {
  
  let temp = $('<p>').html('hello')
  addToDiv('hello',temp.clone());
  addToDiv('hello',temp.clone());

});
Nisha Dave
  • 669
  • 1
  • 9
  • 25