javascriptjqueryjquery-clone

using jquery remove part of a cloned element


having a difficult time removing a div inside of a cloned element. run the snippet and notice the do not clone me part gets appended even though it is removed.

let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
                clone me
                <div class="noClone">
                 do not clone me
                </div>
                <button class="clonebtn"> clone it </button>
             </div>`

$(document).ready(function() {
  let content = $(myhtml);
  $('.row').append(content);

  $('.row').on('click', '.clonebtn', function() {
    let container = $(this).closest('.mycontainer');
    let clonedContainer = container.clone();
    clonedContainer.remove('.noClone');
    $('.row').append(clonedContainer);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">

  </div>
</div>

or run the fiddle here https://jsfiddle.net/k6jz9xe2/3/


Solution

  • let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
                    clone me
                    <div class="noClone">
                     do not clone me
                    </div>
                    <button class="clonebtn"> clone it </button>
                 </div>`
    
    $(document).ready(function() {
      let content = $(myhtml);
      $('.row').append(content);
    
      $('.row').on('click', '.clonebtn', function() {
        let container = $(this).closest('.mycontainer');
        let clonedContainer = container.clone();
        clonedContainer.find('.noClone').remove();
        $('.row').append(clonedContainer);
      })
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
      <div class="row">
    
      </div>
    </div>