Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery split long ul list in smaller lists

I have a long UL list I need to break up in smaller lists containing about 20 items each.

I was thinking I could use something like

$(function() {
    $("ul li:nth-child(20n)").after("</ul><ul>");
});

but that's not the case. Any idea how to use jQuery in a way that uses minimal CPU?

like image 831
Lezz Avatar asked Oct 29 '09 15:10

Lezz


2 Answers

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

like image 178
Alex Sexton Avatar answered Sep 25 '22 20:09

Alex Sexton


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.

like image 34
cletus Avatar answered Sep 24 '22 20:09

cletus