Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone() the first class in jquery

Tags:

jquery

clone

$('.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?

like image 856
user195257 Avatar asked Mar 06 '12 16:03

user195257


People also ask

What does clone do in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.

What is the use of clone in JavaScript?

clone() function is used to create a shallow copy of the given object. The nested objects or arrays will be copied using reference, not duplicated.

How append clone in jQuery?

Copy/Paste with clone() & append() using jQuery You can copy an element from one place to another using the clone() function in jQuery. First you make a copy using the clone() function then you use the appendTo() function to indicate where you want the copy placed.

How do you copy an object in jQuery?

Projects In JavaScript & JQuery To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.


2 Answers

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')
like image 83
Anthony Grist Avatar answered Oct 18 '22 02:10

Anthony Grist


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();
like image 5
Sarfraz Avatar answered Oct 18 '22 04:10

Sarfraz