I want a div
to be duplicated after itself when a button
is clicked. I found JS solutions but I need a jQuery one and I'm really bad at it.
Can anyone help me please?
That's what I have:
<div class="example-1">
<div class="example-2">
<p>Example one</p>
<p>Example two</p>
<button class="btn-copy">Copy</button>
</div>
</div>
That's what I need (after click):
<div class="example-1">
<div class="example-2">
<p>Example one</p>
<p>Example two</p>
<button class="btn-copy">Copy</button>
</div>
<div class="example-2">
<p>Example one</p>
<p>Example two</p>
<button class="btn-copy">Copy</button>
</div>
</div>
To duplicate a div onclick event with JavaScript, we can call cloneNode` to clone an element. Then we can set the onclick property of the cloned element to the same event handler function as the original element. to add a div. Then we deep clone the element by calling cloneNode with true .
To clone a div and change its id with JavaScript, we can use the cloneNode method on the div. Then we can set the id property of the cloned element to set the ID. to add the div.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.
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.
Make use of .clone()
to copy the div and .after()
to append. Since you are using class you may want to copy only one div, in that case you should use .closest()
. Also you need to pass a boolean parameter to clone so that all data and event handlers will be attached to cloned element.
$(function(){
$(".btn-copy").on('click', function(){
var ele = $(this).closest('.example-2').clone(true);
$(this).closest('.example-2').after(ele);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example-1">
<div class="example-2">
<p>Example one</p>
<p>Example two</p>
<button class="btn-copy">Copy</button>
</div>
</div>
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