Jquery group every third div

I have the following structure, one external div (#results) and about 20 divs with a class event. I want to group every 3 events and wrap a div called outer around them,

<div id="result"> <div class="event"> <div class="date">8 April</div> <div class="eventname">my title</div> <div class="link">my link goes here</div> </div> // lots more events here </div> 
+4
source share
3 answers

Try:

 while ($('#result > .event').length > 0) { $('#result > .event:lt(3)').wrapAll('<div class="wrap"></div>') }โ€‹โ€‹โ€‹โ€‹ 

http://jsfiddle.net/rxxjp/

+6
source

Here's one approach: http://jsfiddle.net/vM9KM/4/

 $('#result').children('div.event:nth-child(3n+1)').each(function(i,el) { $(this).next().andSelf().next().andSelf().wrapAll('<div class="outer">'); });โ€‹ 

http://api.jquery.com/nth-child-selector/

+4
source

I used the splice and wrapAll to group 3 wrapAll and wrapped them inside <div class="wrapper" ></div>

Demo

 var events = $('#result .event'); while (events.length >= 3) { $(events.splice(0, 3)).wrapAll('<div class="wrapper" />'); } //wrap the remaining < than 3 div inside wrapper $(events.splice(0, events.length)).wrapAll('<div class="wrapper" />'); 
+1
source

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


All Articles