Search code examples
javascriptjqueryappendclone

jQuery cloned element is only appending the cloned item once inside of a loop


I am attempting to clone a set of text based on the numerical input of a number field. It seems that the code I've got is only appending the item one time into the .wrap element. Is there a limitation with .clone() or something else that I'm overlooking that would only append the item once?

What I Expect to Happen:
What I expect to happen in the code below is, the .duplicate value is updated (let's say to 3), the .target element is cloned, then the .wrap element is emptied, and the loop runs and appends 3 clones stored in $clone. The final .wrap element should contain 3 <h2>Target</h2> elements.

What is Happening:
The above appears to happen, but in the end only 1 <h2>Target</h2> elements are appended onto the .wrap element.

Code:

$( 'body' ).change( '.duplicate', function() {
	
  var count  = $( '.duplicate' ).val(),
      $clone = $( '.target' ).clone(),
      i      = 1;

  $( '.wrap' ).html( '' );

  while ( i <= count ) {

    $( '.wrap' ).append( $clone );

    i++;

  }

} );
.duplicate {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<input type="number" class="duplicate" value="1" min="1" max="5">

<div class="wrap">
  <div class="target">
    <h2>Target</h2>
  </div>
</div>


Solution

  • You need a new clone each iteration otherwise you are simply moving the original one around each time

    Also once you have more than one of that class you only want to clone one of them

     $clone = $( '.target' ).first().clone()
    
     while ( i <= count ) {
         $( '.wrap' ).append( $clone.clone() );