Webistrate - Draw Your Own Conclusions

jQuery: Splitting an unordered list into multiple columns

Posted by Jamie Munro | November 21, 2011 | Tags:


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?


  • Test 1
  • Test 2
  • Test 3


  • Test 1
  •  Test 2
  •  Test 3

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:

<ul id="column">

<div id="columns"></div>

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

for (var i = 0; i < total; i += count) {
$("#columns").append('<ul id="column' + column + '"></ul>');
$("#column" + column).html($("#column li").splice(0, count));


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!


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books