最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cloning an element and adding it to Dom multiple times - Stack Overflow

programmeradmin1浏览0评论
//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
//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
Share Improve this question edited Mar 16, 2010 at 6:02 sth 230k56 gold badges287 silver badges370 bronze badges asked Mar 16, 2010 at 5:58 Praveen PrasadPraveen Prasad 32.1k20 gold badges76 silver badges106 bronze badges 1
  • 1 @Praveen In the future, if you don't get an answer to a question quick enough, don't post a new one. I just finished answering your original question about a minute after you posted it again here. -- Additionally, if you want to simplify your question, just edit the original one. Voting to close this as a duplicate. – Doug Neiner Commented Mar 16, 2010 at 6:04
Add a ment  | 

2 Answers 2

Reset to default 7

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
}

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)

  1. 暂无评论