Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Appending an Object multiple times

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!

like image 899
VIDesignz Avatar asked Sep 19 '14 17:09

VIDesignz


Video Answer


3 Answers

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());
like image 133
plalx Avatar answered Oct 19 '22 06:10

plalx


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.

like image 21
Stryner Avatar answered Oct 19 '22 05:10

Stryner


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

like image 1
Ehsan Sajjad Avatar answered Oct 19 '22 07:10

Ehsan Sajjad