powered by Slim Framework
enhanced by Nesbot.com

jQuery: Splitting an unordered list into multiple columns

Published on Nov 21, 2011 by Jamie Munro

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?

E.g.

  • Test 1

  • Test 2

  • Test 3


Becomes:










  • 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">
<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>


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.

Summary


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!

Tags: Javascript | jquery

<- jQuery: Manipulating an array of HTML elements with $.map()  Home MVC 3: Posting form variables that are not strongly typed -> 
blog comments powered by Disqus