JQuery wrap after x number of elements

I have a UL that contains any number of LIs. I am trying to create some jQuery code that will parse the original UL and wrap the UL and another LI after every 5 source LIs.

HTML launch:

<ul id="original_ul"> <li class="original_li">..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> </ul> 

Required HTML:

 <ul id="processed_ul"> <li class="new_wrap_li"> <ul class="new_wrap_ul"> <li class="original_li">..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> </ul><!-- end new wrap ul --> </li><!-- end new wrap li --> <li class="new_wrap_li"> <ul class="new_wrap_ul"> <li class="original_li">..</li> <li>..</li> <li>..</li> <li>..</li> <li>..</li> </ul><!-- end new wrap ul --> </li><!-- end new wrap li --> </ul><!-- end processed ul --> 

I use the .each function to go through the LIs and add them to the new processed ul stored inside the temporary div ... now I just need to wrap new LIs and ULs around every 5 LIs.

Thanks in advance!

Al

+6
javascript jquery
source share
4 answers

You can do it:

 var lis = $("#original_ul li"); for(var i = 0; i < lis.length; i+=5) { lis.slice(i, i+5) .wrapAll("<li class='new_wrap_li'><ul class='new_wrap_ul'></ul></li>"); } 

This holds them in the same #original_ul element, but you can just change the identifier if necessary. This approach generates the exact html output you have in the question, besides the id at the top of the <ul>

+18
source share
 jQuery('ul#original_ul').attr('id', 'processed_ul') .find('li:nth-child(5n)').each(function() { $(this).prevAll('li').andSelf() .wrapAll('<li class="new_wrap_li"><ul class="new_wrap_ul"></ul></li>'); }); 
+4
source share

You can use a loop.

For example: (Untested)

 while($('ul#original li').length) { var newContainer = $('<li class="new_wrap_li"><ul class="new_wrap_ul" /></li>') .appendTo('#processed_ul'); $('ul#original li:lt(4)').detach().appendTo(newContainer.children('ul')); } 
+3
source share

Something like this will do this:

 $('#original_ul').find('li:nth-child(5n)').each(function(){ $(this).prevAll('li').andSelf() .wrapAll('<ul class="new_wrap_ul"></ul>'); }).end().find('ul').wrap('<li class="new_wrap_li"></li>') .find('li:first-child').addClass('original_li'); 
0
source share

All Articles