jQuery wrap every X elements in div

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

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

<
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 03:39

    Try this. A simple solution..

    var h3s = $('h3');   // caching all h3 tags
    
    // looping over h3 tags
    $.each(h3s, function(i, hs) {
    
        // selecting div.item between two h3
        // for example
        // div.item between this (current h3) and h3:eq(1) (next h3) and so on
    
        var divs = $(this).nextUntil($('h3').eq(i+1), 'div.item');
    
        // looping with divs
        $.each(divs, function(i, el) {
    
            // checking for div.item
            // to group for wrapping
    
            if(i % 3 == 0) {
                divs.slice(i , i+3).wrapAll('
    '); } }); });

    Working sample

    Related refs:

    • .nextUntil()

    • wrapAll()

    • .slice()

    • .each()

提交回复
热议问题