jQuery split long ul list in smaller lists

Solution 1:

I would create document fragments with your removed lis and then reappend them to the location you want them. In this case, I reappended them to the body:

$(function(){
  var $bigList = $('#bigList'), group;
  while((group = $bigList.find('li:lt(20)').remove()).length){
    $('<ul/>').append(group).appendTo('body');
  }
});

Live Demo is at: http://jsbin.com/ejigu/33

Solution 2:

Nothing quite that simple (that I'm aware of at least) unfortunately. Try this as an alternative:

$(function() {
  $("ul").each(function() {
    var list = $(this);
    var size = 3;
    var current_size = 0;
    list.children().each(function() {
    console.log(current_size + ": " + $(this).text());
      if (++current_size > size) {
        var new_list = $("<ul></ul>").insertAfter(list);
        list = new_list;
        current_size = 1;
      }
      list.append(this);
    });
  });
});

You could no doubt turn this into a function that takes the chunk size as an argument but I leave that as an exercise for the reader.