开发者

How to clone only one of multiple nested elements

How do I find if the div I'm cloning has more than one of a child div with a certain class, and if so only clone one of them.

Say the cloned div is .diseaseCon, and the child div(s) is .symptomCon, in the cloning action, how can I detect if there's more 开发者_如何学编程than one .symptomCon divs and only clone one if there are?


e.g. find first .diseaseCon and clone it with only cloning the first .symptomCon too (actually I remove all .symptomCon but the first but that amounts to the same)

$('.diseaseCon').clone().find(".symptomCon:not(:first)").remove();

If you want to clone it and e.g. then append it to the body either use

$('.diseaseCon').clone().find(".symptomCon:not(:first)").remove().end().appendTo("body");

or

$('.diseaseCon').clone().appendTo("body").find(".symptomCon:not(:first)").remove();

Depending on the syntax you like more (where the first syntax should be faster as all operations are done on a fragment and only then the dom is modified

And you can replace :not(:first) with :gt(0) too. Or if you want to keep another symptom but the first use :not(:eq(X)) where X is the index of the symptom you want to keep


If you are cloning the parent DIV, I think you need to remove all but one of the cloned inner DIVs after you are done cloning.

 var klone = $('.diseaseCon').clone();
 klone.find('.symptomCon:gt(0)').remove();
 ...now do something with the clone...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜