Sorting Elements with jQuery

Whilst refactoring a jQuery plugin today, I came across a method that placed a list item into an unordered list at a specific point, so that all the items remained in alphabetic order. This long method seemed completely convoluted and slow to me and I decided that there must be an easier way to keep the list in alphabetical order.

There are existing plugins for sorting elements but I never like to just pile on the 3rd party plugins as that means more javascript files to include in a page. Besides, I was sure it should not be difficult.

It soon occured to me that jQuery has the built-in ability to return the elements as an array, using the .get() method and from there, it was not too long before I had my streamlined code to sort the list element alphabetically:

var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

I utilise the javascript array.sort method to sort the elements in the array and then using the jQuery append() method,  reorder them in the actual list element.

61 Comments to “Sorting Elements with jQuery”

  1. OMA 22 May 2014 at 4:31 am #

    Thanks for this snippet. Simple and elegant, as it should be :)

  2. Alone 12 March 2014 at 10:09 am #

    Thanks, works fine!

  3. Roshdy 18 November 2013 at 8:36 pm #

    I have a problem with this function,
    my list is:
    item 1
    … // list of numbers
    item 23
    however, when i sort from 1 -> 9, it’s working, but for double digit postfix it doesn’t!
    any suggestions?

  4. suresh 18 September 2013 at 9:13 pm #

    its nice

  5. carp3tshark 21 February 2013 at 3:22 pm #

    Has any one done any modifications to this that will sort dates correctly? i.e 12/5/2013 – I suppose one needs to know the region to know if they are mm/dd/yyyy or dd/mm/yyyy and do the proper thing.

    I’ve been looking at:
    http://tablesorter.com/docs/

  6. Cosmin 14 September 2012 at 8:26 pm #

    well your display cut out the elements.

    first example is:

    a div class=test_div
    here span with text 1 in it
    span with text 2 in it
    etc
    close div
    last an input button with id=SomeID class=StartSort value=Sort
    ————-
    for the second one

    a div with class=example_two
    span with attribute lang=0, in it Sunday
    span with attribute lang=1, in it Monday
    etc
    close div
    a input button with class=StartSortSecond id=SomeIDSecond value=Sort.

    ——
    sorry for this.

  7. Cosmin 14 September 2012 at 8:11 pm #

    Ok. this is absolutely amazing.

    but here are some stuff to consider:
    1. It needs to work on any combination of elements.
    (ex div->span, td->div etc)
    2. It must sort by other criteria as well because not all the time the sorting is text based.

    So, because your ideea helped so much, i’ll give you mine too…
    __________________________
    ex 1:

    text 1
    text 2
    text 3
    text 4

    your function would be:

    function SortByName(element,child_type){
    var mylist = $(element),listitems = mylist.children(child_type).get();
    listitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA compB) ? 1 : 0;
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
    }

    call it like this:
    $(‘#SomeID’).click(SortByName($(‘.test_div’),’span’));
    or
    $(‘.StartSort’).click(SortByName($(‘.test_div’),’span’));

    but for example you have a display with days of the week like this:

    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

    at this point your function would mess it up… sorting by name is not a good option.

    so we use any attribute of the element we’re displaying as our sort criteria.

    i added lang for span because it won’t mess the validation standard for the page.

    it would be:

    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

    now the function is:

    function SortListByAttr(element,child_type,attribut){
    var mylist = $(element),listitems = mylist.children(child_type).get();
    listitems.sort(function(a, b) {
    var compA = $(a).attr(attribut).toUpperCase();
    var compB = $(b).attr(attribut).toUpperCase();
    return (compA compB) ? 1 : 0;
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
    }

    call it like this:
    $(‘#SomeIDSecond’).click(SortListByAttr($(‘.example_two’),’span’,’lang’));
    or
    $(‘.StartSortSecond’).click(SortListByAttr($(‘.example_two’),’span’,’lang’));

    I hope it helps!

  8. mark 10 July 2012 at 1:15 am #

    Nice one. Just what I was looking for and I totally agree about 3rd party bloatware

  9. santhosh 24 May 2012 at 8:16 pm #

    Hi,
    This one not working in IE8.Let me know any solution for resolve this.
    Advance Thanks

  10. ross 16 May 2012 at 2:08 am #

    Excellent, thanks.

  11. M Enock 20 March 2012 at 8:26 pm #

    Thank you very much for a great solution!


Leave a Reply