开发者

How do i group a certain number of elements with jQuery?

I need some quick help on selecting items with jQuery. It might be a very simple solution, but... I can't see one right one besides cloning and duplicating elements. So, here we go. I have this kind of structure on a page:

http://content.screencast.com/users开发者_JS百科/iamntz/folders/Jing/media/2fa05c60-f4fc-4178-b9b6-187831e1ca31/2010-11-22_1741.png

I want to group each six elements into a wrapper element, in order to have .quotesWrapper > (.sixQuoteWrapper > .quote * 6) * 4.

Any idea how i could achieve this? Thanks!


@John Hartsock's solution is concise but inefficient because of the number of times the selectors are run. I would suggest a variation on his:

var i = 0, 
    quotes = $("div.quoteWrapper").children(),
    group;

while ((group = quotes.slice(i, i += 6)).length) {
    group.wrapAll('<div class="sixQuoteWrapper"></div>');
}

This solution runs a shorter selector just once and retrieves the children, making it faster.

Working demo: http://jsfiddle.net/AndyE/FFf6z/


I'm sure i could get this without an each if i gave it a few more mins, but this works.

Here is a js fiddle

$('.quotesWrapper .quote.split').each(function(){
    $(this).nextUntil('.quote.split')
        .andSelf()
        .wrapAll('<div class="wrap" />')
});


I believe this is what you want. Essentially you loop through untill you have no more div.quote items under div.quoteWrapper. This is using the :lt() selector

while ($("div.quoteWrapper > div.quote").length) {
  $("div.quoteWrapper > div.quote:lt(6)").wrapAll('<div class="sixQuoteWrapper"></div>');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜