jQuery Sort Elements

A neat trick I have been using on a few of my more recent projects is the ability to sort elements on a page using jQuery. It is surprisingly simple when you think about how jQuery works. Since each element is just inside an an array ( $(‘.classes’) is actually an array to jQuery. ). So all we have to do is a standard sort using javascript.

Here I am using a data attribute (‘data-name’) to sort alphabetically. This also works for numbers.

In this instance I am first sorting by value and then by name. So if 2 elements had the same value it would sort them by name.

Another handy part of this is the reverse function.

Just add this function declaration anywhere jQuery is allowed and you can now reverse the order of the elements!

Here is a typical use for these functions.

There ya go! All you need to get started sorting elements with jQuery!