By Sam Deering

jQuery Convert a List to Columns – $.list2Columns()

By Sam Deering


I thought I would share with you a jQuery function I wrote to convert a list (UL or OL) into columns. Could be quite useful if your list comes in and reads from top to bottom it will separate the list items into vertically spaced columns.


The Code

    list2Columns: function(numCols)
        var listItems = $(this).html().match(/(
  • .+)/igm); /* get the list data */ var listHeader = $(this).html().match(/(
      /igm); var numListItems = listItems.length; var numItemsPerCol = Math.round(numListItems / numCols); /* divide by the number of columns requires */ var currentColNum = 1, currentItemNumber = 1, returnHtml = '', i = 0; $(this).empty(); /*clean previous content */ /* append the columns */ for (i=1;i
    '); } /* append the items to the columns */ $.each(listItems, function (i, v) { if (currentItemNumber Usage [js] $('#countries').list2Columns(4);
  • Demo

    • Afghanistan
    • Albania
    • Algeria
    • Australia
    • Austria
    • Bahamas
    • Bahrain
    • Bangladesh
    • Barbados
    • Belarus
    • Canada
    • Comoros
    • Congo
    • Cook Islands
    • Costa Rica

    • Great.. =D
      I redid your plugin, in another way and for the same purpose.

      I hope you enjoy, =)

      • jquery4u


        Great job mate, good to see some coding from Brazil!

        There is a small bug where it will output null for 5+ columns, it’s not you, apparent in my code too! <-- click run Maybe it's just me but I hate using while loops unless i absolutely have to, maybe it's back to my C++ days. This was a first version, it could be improved but it's a nice little function to have! :) Thanks for sharing! Cheers, Sam

    • schadeck

      I have noticed that the after the function splits the ul, it loses an li for each column created… something to look into.

    • tproli

      Correct me if I’m wrong but the “else” part should also append the current item. The actual item (v) is skipped when moving to a new column.

    Get the latest in JavaScript, once a week, for free.