user195257
user195257

Reputation: 3316

Clone() the first class in jquery

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

I have some form inputs in a div.immediate-whiskypack-inputs, I want to clone this and append it to div#whiskypacks. The above function clones each div class, is there a way of cloning just one of the div's?

Upvotes: 13

Views: 12990

Answers (3)

gdoron
gdoron

Reputation: 150253

You didn't mention which div you want to clone, so I guess you don't care which one...
first() function will grab the first element:

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

If you do care which element you want to clone, use the eq(index) function:

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

eq docs:

eq(index) index- An integer indicating the 0-based position of the element.

Upvotes: 5

Anthony Grist
Anthony Grist

Reputation: 38345

Simply modify your selector so that it returns the single element that you want to clone. If you're interested in the first match, then use:

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

rather than

$('.immediate-whiskypack-inputs')

Upvotes: 17

Sarfraz
Sarfraz

Reputation: 382696

The above function clones each div class, is there a way of cloning just one of the div's?

Use eqDocs:

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

The eq needs index of element starting from 0. So if you want to append first one, use 0, second, use 1, third, use 2 and so on.

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

// 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();

Upvotes: 7

Related Questions