Duikboot Duikboot - 4 months ago 7
jQuery Question

Duplicate div outside the current div

Problem

I am trying to clone a div when a user click the add button. The problem is that I am cloning right now the div inside the current one. I would like to add it to the .wrapper div but that fails. I tried already a few other things like appendTo('.wrapper'), but without success.

You can see when you click the add button, the indentation is not correct from the fields that are being cloned.

Example https://jsfiddle.net/duikboot/1sakxpzq/

Code where I do the clone:

var pd = $('.product_data').last().clone();
var id_count = 0;

$(document).on('click', '.add_item', function() {
var clone = pd.clone().prop('id', 'product_' + id_count);
$(this).prevAll('.product_data').first().append(clone.hide());
clone.slideDown('fast');
id_count++;
});


Thanks for all help.

Answer

.append() and the content inside selected container as last child. You need to use .after() for adding content as next sibling:

$(document).on('click', '.add_item', function() {
  var clone = pd.clone().prop('id', 'product_' + id_count);
  $(this).prevAll('.product_data').first().after(clone.hide());
  clone.slideDown('fast');
  id_count++;
});

Working Demo

Comments