$('.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?
jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.
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.
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.
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.
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')
The above function clones each div class, is there a way of cloning just one of the div's?
Use eq
Docs:
$('.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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With