webmonkey237 webmonkey237 - 7 months ago 48
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.


$('.button').click(function () {



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');

Here's a fiddle.