如何组合具有相同类的两个div – jQuery

我有这样的div结构

如何让它们合并/组合两个div“itemRow”? 就像这样

 

使用jQuery

首先,您的itemRow> item没有结束标记。

你需要做的是遍历所有具有相同类的元素,将第一个元素保存为基类,然后将具有相同类的其他元素的子元素附加到基本元素:

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

通过这种方式,您可以将最终结果作为单独的变量获得,您可以随意使用它,而原始元素保持不变。

我在这里创造了一个小提琴: http : //jsfiddle.net/dejvidpi/qEBZ4/

尝试

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

演示: 小提琴

你可以这样做

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

小提琴

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

Tiny插件,它接受数组中的第一个元素,并将所有其余元素附加到其中。 使用它像$("div").combine();

对于将来推荐的人, AdrianCooney的答案的固定和改进版本:

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

你可以这样称呼它

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

的jsfiddle