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

后端 未结 5 1304
悲&欢浪女
悲&欢浪女 2020-12-11 09:24

I have a div structure like this

相关标签:
5条回答
  • 2020-12-11 09:36

    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

    0 讨论(0)
  • 2020-12-11 09:50

    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

    0 讨论(0)
  • 2020-12-11 09:54
    $.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();.

    0 讨论(0)
  • 2020-12-11 09:56

    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/

    0 讨论(0)
  • 2020-12-11 09:57

    Try

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

    Demo: Fiddle

    0 讨论(0)
提交回复
热议问题