Search code examples
javascriptjqueryhtmlappenddetach

Detach and append divs/html jquery


I thought this would be kinda straightforward but i cant wrap my head around this. I got to following html:

<div id="foo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>     
</div>

<div id="bar">
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test">test4</div>
</div>

I need to grab/detach the div's .test and put/append them into the .item div's. So the first div .test needs to go in the first div .item, the second div .test to the second div .item etc. So it becomes:

<div id="foo">
<div class="item">1<div class="test">test1</div></div>
<div class="item">2<div class="test">test2</div></div>
<div class="item">3<div class="test">test3</div></div>
<div class="item">4<div class="test">test4</div></div>    
</div>

Now i found some jquery code and i came to this:

var child = $('#bar').find("div").eq(0);
var parent = $('#foo').eq(0);

child.detach();
parent.append( child );

This works but as suspected, it detaches/appends the first div. Now i need to detach/append them all one by one and from reading a lot of topics, i think i need to put a loop/each in there somewhere but i have no idea how and im not getting any closer after screwing around for hours.

Anyone who can put me in the right direction with this?


Solution

  • On solution is to get both collections and iterate over one of the collections. Also note that you don't need to use .detach. .append will already do that.

    var $fooItems = $("#foo .item");
    var $barTests = $("#bar .test");
    
    $fooItems.each(function(index, el) {
        $(this).append($barTests.eq(index));
    });
    

    Example Fiddle