Appending a DOM element twice (jQuery)

Try clone. This, as the name implies, will copy the $foo element and not move, like append will do.

$(function(){
    var $foo = $("<foo>HI</foo>");
    $("#a").append($foo.clone());
    $("#b").append($foo.clone());
});

But, why not just use this?

$("#a,#b").append($foo);

This will also work :)

Here's a demo for both these situations : http://jsfiddle.net/hungerpain/sCvs7/3/


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 = $("<foo>HI</foo>");
    $("#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 = $("<foo>HI</foo>");
    $("#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 ("<foo>HI</foo>") directly, like:

var foo = "<foo>HI</foo>";
$("#a").append(foo);
//...