Search code examples
htmljqueryclone

Cloning parent and its first + last child in jQuery


Say I have the following the markup:

$('button').click(function() {
  let row = $('div.row');

  let clonedRow = row.clone(true);

  clonedRow.appendTo('body');
});
.row {
  border: 1px solid black;
  margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>append</button>
<div class="row">
  <div class="first">append me!</div>
  <div class="item">DONT append me</div>
  <div class="item">DONT append me</div>
  <div class="last">append me!</div>
</div>

I can achieve this by using clone() multiple times, but I'm looking for a clean solution that can do it with as little methods/functions as possible. Has to be in jQuery and not vanilla JS.


Solution

  • You can use the remove() method to remove the .item elements from the cloned content:

    $('button').click(function() {
      let $row = $('div.row:first').clone(true);
      $row.find('.item').remove();
      $row.appendTo('body');
    });
    .row {
      border: 1px solid black;
      margin-bottom: 5px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>append</button>
    <div class="row">
      <div class="first">append me!</div>
      <div class="item">DONT append me</div>
      <div class="item">DONT append me</div>
      <div class="last">append me!</div>
    </div>