How to combine two divs that have the same class - jQuery

advertisements

I have a div structure like this

<div class="items">
    <div class="itemRow">
        <div class="item">
        <div class="item">
        <div class="item">
    </div>
    <div class="itemRow">
        <div class="item">
        <div class="item">
        <div class="item">
    </div>
</div>

How can I make them merge/combine the two divs "itemRow"? to be like this

<div class="items">
    <div class="itemRow">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
        <div class="item">
    </div>
</div>

using jQuery


First of all, your itemRow > item(s) have no closing tag.

What you need to do is go through all of the elements with same class save the first as a base one, and then append the children of the other elements with same class to the base element:

var endelement;
$.each($('.itemRow'), function(index, value) {
    if (index == 0)
        endelement = $(this).clone();
    else
    {
        $.each($(this).children('.item'), function(i, v){
            $(this).clone().appendTo(endelement);
        });
    }
});

$('.endProduct').html(endelement[0].outerHTML);

This way you get the end result as seperate variable and you can do with it whatever you want, while the original elements stay as they were.

I've created a fiddle here: http://jsfiddle.net/dejvidpi/qEBZ4/