views:

91

answers:

2
//I am cloning a dom element and inserting it in dom element multiple times

    <div class='toBeCloned'>some text</div>
    <div id='target'></div>

    var _clone=$('.toBeCloned').clone(true);//create clone
    var _target=$('#target'); //this is target

    _target.append(_clone); //append target
    _target.append(_clone); //append target
    _target.append(_clone); //append target

//this should add 3 elements but it's adding only one
+5  A: 

append is a bit odd here - it moves the element, but it might also clone it if you append it to more than one element (eg $(div).append will clone the element for every div).
If you want to create 3 elements, simply call clone 3 times:

var _clone=$('.toBeCloned');
var _target=$('#target'); //this is target

for(var i=0;i<3;i++){
    _target.append(_clone.clone(true)); //append target, clone every time
}
Kobi
+1 Great answer Kobi. Glad you added the explanation as its very clear!
Doug Neiner
A: 

It is conceptually strange to insert a single element in the DOM multiple times, since a DOM element can have max one parent (poor elements!). Event if you insert it into the same container, it is still very strange to be one's own sibling, so that is equally ruled out.

That is why an element is removed from the structure (if it is in one) whenever it is added somewhere else.

I spoke of pure js and the DOM now.

I was briefly under the impression that jQuery's append does not ever clone elements, but it "conveniently" does so if it is invoked on a set of elements.

npup
`append` can remove the element from its location **and** clone it multiple times, by appending it to multiple elements. (see my explanation above and an example here: http://jsbin.com/udiya ). In this case, the OP (original poster) is appending to a single element, so it is just moved nowhere for 3 times.
Kobi
Oh yeah, sorry. If the selector returns a set.jQuery just hid the iteration from my eye since it seems to adapt to whatever it was invoked on (single element or a set).
npup