jQuery: Splitting an unordered list into multiple columns

j

I was recently answering some questions on Stackoverflow and an intriguing question came up. How do I split an unordered list into a multiple lists to turn them into columns? Using a combination of a JavaScript array and jQuery, I will leverage splice, append, html and a common for loop.

E.g.
Test 1
Test 2
Test 3

Becomes:

Test 1 Test 2 Test 3

Setting up the unordered list to be split

One of the keys of course is speed and not duplicating/cloning the DOM elements because it will be extremely inefficient. After some trial and error, here is the final working product:

[code]
<ul id=”column”>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

<div id=”columns”></div>

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js”></script>
<script>
$(document).ready( function() {
var total = $(“#column li”).size();
var count = 2;
var column = 0;

for (var i = 0; i < total; i += count) {
column++;
$(“#columns”).append(‘<ul id=”column’ + column + ‘”></ul>’);
$(“#column” + column).html($(“#column li”).splice(0, count));
}

$(“#column”).remove();
});
</script>
[/code]

The li tags from the #column ul element are looped through and spliced out of the existing array and appended to a new column ul tag. It’s nice and quick because it will only loop once for each column that is being created.

In the above example, 2 li tags are being created in each ul column. Changing this number will adjust the results accordingly. The final output will be 2 items in the first two and then the left over 1 in a third column.

The splice function works perfectly here because it removes the elements from the existing array and returns them so they can be inserted into the new column. No cloning and minimal number of loops!

About the author

By Jamie

My Books