jQuery wrap every X elements in div

后端 未结 4 1024
栀梦
栀梦 2020-12-18 03:17

I have a list of elements (divs) preseded by a H3 tag

<
4条回答
  •  自闭症患者
    2020-12-18 03:35

    I've ended up with this and it's working

    $(function(){
        var h3=$('h3');
        h3.each(function(){
            var divs=$(this).nextUntil('h3');
            var row_wreapper=$('
    '); while(divs.length) { var grp=divs.splice(0, 3); var row=$('
    '); $(grp).each(function(){ row.append($(this)); }); row_wreapper.append(row); } $(this).after(row_wreapper.html()); }); });​

    DEMO or with a little extra checking of item class DEMO.

    Or

    $(function(){
        var h3=$('h3');
        h3.each(function(){
        var divs=$(this).nextUntil('h3');
        var row_wreapper=$('
    '); while(divs.length) { var grp=divs.splice(0, 3); var row=$(grp).wrapAll('
    '); if(row.children().length) row_wreapper.append(row); } $(this).after(row_wreapper.html()); }); });​

    DEMO.

提交回复
热议问题