EmptySnake EmptySnake - 1 month ago 9
Javascript Question

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>

Answer

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>