Appending a DOM element twice (jQuery)

Tags: , , , ,

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


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


    var $foo = $("<foo>HI</foo>");


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.


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:

    var $foo = $("<foo>HI</foo>");

You could also append the html from $foo, which would just take a copy of the dom within it rather than the element itself:

    var $foo = $("<foo>HI</foo>");

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>";

Source: stackoverflow