Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate div on click with jQuery?

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>
like image 202
EmptySnake Avatar asked Oct 27 '16 04:10

EmptySnake


People also ask

How can I duplicate a div onclick event?

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 .

How do I clone a div?

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.

How do you copy the content of a div into another div using jQuery?

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.

How do you clone an object in 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.


1 Answers

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>
like image 154
Shubham Khatri Avatar answered Sep 25 '22 14:09

Shubham Khatri