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?
I would create document fragments with your removed li
s 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With