Home > Blockchain >  Cloning parent and its first last child in jQuery
Cloning parent and its first last child in jQuery

Time:06-15

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 >
  <div >append me!</div>
  <div >DONT append me</div>
  <div >DONT append me</div>
  <div >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.

CodePudding user response:

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 >
  <div >append me!</div>
  <div >DONT append me</div>
  <div >DONT append me</div>
  <div >append me!</div>
</div>

CodePudding user response:

First you have to select row, then clone that row & then remove .items elements from that content by remove() method & then append that to the body.

 $('button').click(function(e) {
      e.preventDefault();
      let row = $('div.row:first');
    
      let clonedRow = $(row).clone(true);
      $(clonedRow).find("div.item").remove();
     $(clonedRow).appendTo('body');
    });
  • Related