prevent jQuery from creating duplicate clones via .clone()
So I have an element with a few children elements and when I attempt to use jQuery.clone() on the parent it clones the parent (with all of it's children) and then clones the kiddos once again. To clarify with an example:
Javascript:
$(parent).clone(false).appendTo(container);
Original HTML
<parent>
<element1>
<element2>
</p开发者_如何学运维arent>
<container></container>
Modified HTML:
<parent>
<element1>
<element2>
</parent>
<container>
<parent>
<element1>
<element1>
</parent>
<element1>
<element2>
</container>
Now, I would need a way to prevent the function from cloning the elements, without using IDs or classes, since I can't predict the content of the parent.
EDIT: Fiddle!
Thank you,
Luna
If you call clone from within an .each()
it's going to go through each selector (in your case you're supplying the class to both the parent and it's child) and duplicate/append each found item. Put simply:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
<div class="container"></div>
$('.parent, .child').each(function(i,e){
$(this).clone().appendTo('.container');
});
Will:
- Find
.parent
(which, by hierarchy) will also find both.child
ren, duplicate them, and append them. - Will find each child and also append them (leaving you with the impression clone is double-duplicating).
Instead, depending on your set-up, just clone the parent, make the modifications, and append that result.
If you're looking to just clone the descendant of .parent, try using a different selector (maybe .parent > .child
to show a direct child relationship). e.g. $('.parent > .child').clone();
(I've posted this as an answer as I felt a comment wasn't sufficient for anyone else who may find this question as a resource)
精彩评论