Clone () first class in jquery

$('.addPack').click(function(){ $('.immediate-whiskypack-inputs').clone().appendTo('#whiskypacks').show(); return false; }); 

I have form input in div.immediate-whiskypack-input, I want to clone this and add it to div # whiskypacks. The above function clones each div class, is there a way to clone just one of the divs?

+4
source share
3 answers

Just change your selector so that it returns the one element you want to clone. If you are interested in the first match, use:

 $('.immediate-whiskypack-inputs:first') 

but not

 $('.immediate-whiskypack-inputs') 
+9
source

The above function clones every div class, is there any way to clone just one of div <? >

Use eq Documents :

 $('.immediate-whiskypack-inputs').eq(0).clone().appendTo('#whiskypacks').show(); 

eq needs an element index starting at 0 . Therefore, if you want to add the first, use 0 , secondly, use 1 , thirdly, use 2 , etc.

If you want to clone the first or last, use the filter selectors :first and :last :

 // clone first $('.immediate-whiskypack-inputs:first').clone().appendTo('#whiskypacks').show(); $('.immediate-whiskypack-inputs').eq(0).clone().appendTo('#whiskypacks').show(); // clone last $('.immediate-whiskypack-inputs:last').clone().appendTo('#whiskypacks').show(); 
+2
source

You did not specify which div you want to clone, so I think you don’t care which one ... The first() function will capture the first element:

 $('.addPack').click(function(){ $('.immediate-whiskypack-inputs').first().clone().appendTo('#whiskypacks').show(); return false; }); 

If you need some element that you want to clone, use the eq(index) function:

 $('.immediate-whiskypack-inputs').eq(theDesiredElementIndex).clone()... 

eq docs :

eq (index) index is an integer indicating the position of element 0.

+2
source

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


All Articles