jQuery: Splitting an unordered list into multiple columns jQuery: Splitting an unordered list into multiple columns

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 1Test 2Test 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:


<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.

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!

Published on Feb 26, 2019

Tags: JavaScript | jQuery Tutorial | remove

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.