Wrapping a div around every three divs

前端 未结 3 1148
渐次进展
渐次进展 2021-01-05 12:35

Say I have 6 child divs and they don\'t have unique identifiers:

3条回答
  •  执笔经年
    2021-01-05 13:25

    There's a small plugin I've written which I use in scenarios like this. It takes a collection, and splits it in to chunks of x (where x is the size of each chunk):

    $.fn.chunk = function( cLen ) {
        var chunks = [];
        while ( this.length ) {
            chunks.push( this.splice(0, cLen) );
        }
        return $(chunks);
    };
    

    It can then be used like this:

    $('.child').chunk(3).each(function() {
      $(this).wrapAll('
    '); });

    Here's a fiddle

    Or, as a plugin for this purpose:

    $.fn.wrapEvery = function( cLen, wrapperEl ) {
        while ( this.length ) {
            $( this.splice(0, cLen) ).wrapAll( wrapperEl );
        }
    };
    

    Which could be used like this:

    $('.child').wrapEvery(3, '
    ');

    Here's another fiddle

提交回复
热议问题