How do I group a certain number of elements using jQuery?

I need quick help when selecting items using jQuery. It may be a very simple solution, but ... I do not see any one correct, except for cloning and duplication of elements. So, we will go. I have a structure like this on the page:

http://content.screencast.com/users/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 to have .quotesWrapper > (.sixQuoteWrapper > .quote * 6) * 4 .

Any idea how I could achieve this? Thanks!

+2
source share
3 answers

I'm sure I can get it without everyone if I gave him a few more minutes, but it works.

Here is js fiddle

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

@ John Hartsock's solution is concise but ineffective due to how many times selectors are triggered. I would suggest an option:

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

This solution works with the short selector only once and returns the children, making it faster.

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

+2
source

I believe that this is what you want. Essentially, you loop until you have more div.quote elements in div.quoteWrapper. This is used : lt () selector

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

Source: https://habr.com/ru/post/1380531/


All Articles