Cloning an element and adding it to Dom multiple times

后端 未结 2 1622
迷失自我
迷失自我 2021-01-23 02:58
//I am cloning a dom element and inserting it in dom element multiple times

    
some text
相关标签:
2条回答
  • 2021-01-23 03:42

    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
    }
    
    0 讨论(0)
  • 2021-01-23 03:45

    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.

    0 讨论(0)
提交回复
热议问题