Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

grouping - jQuery wrap every X elements in div

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

<h3></h3>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<h3></h3>
<div class="item"></div>
<div class="item"></div>

etc...

Using jQuery, I'd like to group every 3 divs (or less) followed by each h3 like this:

<h3></h3>
<div class=row>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>
<div class=row>
    <div class="item"></div>
</div>
<h3></h3>
<div class=row>
    <div class="item"></div>
    <div class="item"></div>
</div>

I tried a solution proposed here: Insert <div> for every 5 elements using Javascript but it obviously grouped ALL the divs. I also tried using ~ selector without any success:

var a = $('h3 ~ div.item');

for( var i = 0; i < a.length; i+=3 ) {
    a.slice(i, i+3).wrapAll('<div class="row"></div>');
}

Any help will be highly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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=$('<div></div>');
        while(divs.length)
        {
            var grp=divs.splice(0, 3);
            var row=$('<div class="row"></div>');
            $(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=$('<div></div>');
    while(divs.length)
    {
        var grp=divs.splice(0, 3);
        var row=$(grp).wrapAll('<div class="row"></div>');
        if(row.children().length) row_wreapper.append(row);
    }
    $(this).after(row_wreapper.html());
    });
});?

DEMO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...