Ryan Barnaby
Ryan Barnaby

Reputation: 169

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

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

Upvotes: 4

Views: 3924

Answers (5)

T J
T J

Reputation: 43156

For someone referring in future, a fixed and improved version of AdrianCooney 's answer:

$.fn.combine = function(selector) {
 var parent = $(this[0]);
 this.each(function(i) {
    parent.append($(this).children(selector));
    if(i>0)
    $(this).remove();    
 });
};

You can call it like

$(".itemRow").combine('.item');

JSFiddle

Upvotes: 0

David Pucko
David Pucko

Reputation: 81

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/

Upvotes: 1

wirey00
wirey00

Reputation: 33661

You can do it like this

$('.itemRow:first') // select first itemRow
   .append($('.item')) // append all .item to first itemRow
   .nextAll('.itemRow') // get all the next .itemRow
   .remove(); // remove the them

FIDDLE

Upvotes: 3

AdrianCooney
AdrianCooney

Reputation: 703

$.fn.combine = function() {
    var parent = $(this[0]);
    this.each(function(elem) {
        parent.append($(elem).html());
    });
};

Tiny plugin that takes the first element in an array and appends all the rest of the elements into it. Use it like $("div").combine();.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var $rows = $('.items .itemRow');
$rows.first().append($rows.not(':first').children())
$rows.not(':first').remove();

Demo: Fiddle

Upvotes: 7

Related Questions