Appending a DOM element twice (jQuery)

Tags: , , , ,



Can someone explain why the following snippet does not add <foo> to both #a and #b?

HTML:

<div id="a"></div>
<div id="b"></div>

JS:

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

jsfiddle

Edit: thanks for the helpful points, the fact that .append() moves the element explains this behavior. Since the element in my application is actually a Backbone View’s .el, I prefer not to clone it.

Answer

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


Source: stackoverflow