David Johns
David Johns

Reputation: 1714

How to clone parent element with all the sub elements in jQuery?

I have the following code to Add new Paragraph when I click on a button. I'm cloning the "sub" div and append it to the "main" div. But with cloning the "sub" div, it is copying only the content of "sub" div which is "inner" div instead copying with the "sub" div. I need to have several "sub" divs after cloning it several times. But now only the first paragraph has "sub" parent div and all the other cloning divs has "inner" parent div. How can I do this?

$("button").on("click", function() {
  $(".main").append($(".sub:last").clone().html());
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

<div class="main">
  <div class="sub">
    <div class="inner">
      <p>
        New Paragraph
      </p>
    </div>
  </div>
</div>

<button>Add new</button>

Upvotes: 0

Views: 899

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44107

You need to add specific arguments if you want a deep copy (see the .clone() docs for more):

$("button").on("click", function(){
	$(".main").append($(".sub:last").clone(true, true));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="main">
  <div class="sub">
    <div class="inner">
      <p>
        New Paragraph
      </p>
    </div>
  </div>
</div>

<button>Add new</button>

EDIT

Above, I removed .html() so the <div class="sub> will be added to the main div, not just the inner div.

Upvotes: 3

Related Questions