I am using jQuery 1.9.0, and my html is:
<div id='div1'>
</div>
<div id='div2'>
</div>
my js:
var input = $("<input type='text'>");
$('#div1').html(input);
$('#div2').html(input);
my understanding of this code is
input is a jQuery object, and I can set div1 and div2 with it separately just like I can assign one variable’s value to many other variables in programming languages.
based on this understanding, what I expect is:
<div id='div1'>
<input type="text">
</div>
<div id='div2'>
<input type="text">
</div>
but I get:
<div id='div1'>
</div>
<div id='div2'>
<input type="text">
</div>
if I just call $('#div1').html(input);, div1 would have input element.
why does div1‘s input element disappear after calling $('#div2').html(input);?
I know how to bypass this problem, but I am eager to know the reason of this behavior.
thanks in advance!
UPDATE:
I appreciate all the guys who answered this problem sincerely, and I have voted up every answer. I have a clue to this issue now, but I am still wondering why different nodes (div1 and div2) can not reference to the same object. In C language, different variables can reference to the same memory address. what’s the difference between these two reference?
The bottom line is that the DOM doesn’t automatically clone your elements when you attach them somewhere on the page. This is not jQuery specific.
Because
inputkeeps referencing the same element, attachinginputto another element later on will detach it from the previous location, thusinputkeeps moving around in the DOM.This is why you have to clone the element before you attach it 🙂