How to clone only one of several nested elements

How to find if the cloning of the div that I am cloning has more than one child div with a specific class, and if so, then only cloning one of them.

Suppose the cloned div is .diseaseCon and the child div (s) is .symptomCon, in the cloning action, how can I determine if more than one .symptomCon divs exists and only clone if there is one?

+4
source share
2 answers

eg. find the .diseaseCon first and clone it only with the cloning of the first .symptomCon (actually I delete all .symptomCon , but the first, but it's the same)

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

If you want to clone it and, for example, then add it to the body or 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 best (where the first syntax should be faster, since all operations are performed on the fragment, and only then dom changes

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

+4
source

If you are cloning a parent DIV, I think you need to delete everything except one of the cloned internal DIVs after you finish the cloning.

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

Source: https://habr.com/ru/post/1304722/


All Articles