tags:

views:

39

answers:

2

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?

+3  A: 

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

jitter
Your second solution was right on target. Good stuff.Thanks a bunch!
eknown
+1  A: 

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...
tvanfosson
Good answer! Thanks
eknown