webmonkey237 webmonkey237 - 4 months ago 17
jQuery Question

jQuery appendTo making multiple copies

I have a basic function that shifts one div into another, when I have multiple divs with the same class name it duplicates the div.

In my fiddle/example at the moment it takes a copy of all four orange squares and puts them inside all of the red squares

What I want is the orange square below each red square to move inside the red square so each red square will only have one orange square inside, the one below it.

FIDDLE

$('.button').click(function () {
$('.orange').appendTo('.red');
});


Thanks

Answer

That's because $('.orange') gets all the divs with the class orange. (There are four.) What you want to do is to loop through the containers and just get the div.orange there.

$('.button').click(function () {
    $('.container').each(function (idx, elm) {
      var $container = $(elm);
      var $red = $container.children('.red');
      var $orange = $container.children('.orange');
      $orange.appendTo($red);
    });
}); 

Here's a fiddle.