Can someone explain why the following snippet does not add
to both #a
and #b
?
HTML:
Because using append
actually moves the element. So your code was moving $foo
into the document at #a
, then moving it from #a
to #b
. You could clone it instead like this for your desired affect - this way it is appending a clone rather than the initial element:
$(function(){
var $foo = $("HI ");
$("#a").append($foo.clone());
$("#b").append($foo.clone());
});
You could also append the html
from $foo
, which would just take a copy of the dom within it rather than the element itself:
$(function(){
var $foo = $("HI ");
$("#a").append($foo[0].outerHTML);
$("#b").append($foo[0].outerHTML);
});
The above examples are assuming you have a more complicated scenario where $foo
isn't just a jQuery object created from a string... more likely it is created from an element in your DOM.
If it is in fact just simply created this way and for this purpose... there is no reason at all to create that jQuery object to begin with, you could simply append the string itself ("
) directly, like:
var foo = "HI ";
$("#a").append(foo);
//...