How To Sort Elements By ID In jQuery

I recently came across an issue wherein I needed to be able to sort a set of HTML elements by their IDs. I was retrieving a wrapped set with jQuery, but didn't know how to sort them.

I found a blog post by a guy named Bill Richards which can be found here. This put me on the right track and allowed me to solve this issue. My solution is a little different than his, but it was his post that showed me the solution to this problem and saved me a lot of time. Also, a comment left there by a guy named Tom helped as well. Thanks guys!

To sort elements with jQuery, all you need to do is create a function that will do the actual sorting (comparing two elements) and then pass the name of this function to the sort() method (using jQuery 1.3.2 or higher).

Here is a function which will sort elements by ID:

function sortByID(a, b)
{
   return a.id > b.id ? 1 : -1;
};

To use this function to sort a wrapped set, you can call it inline with your code which creates the set by passing the name of it to the sort method. For example, to select all images having a tag that begins with imgWildlife and sort them by their full ID (for example, imgWildlife001, imgWildlife002, etc), you could use the following:

var images = $("img[id^=imgWildlife]").sort(sortByID);

To sort by something other than the ID, create a function that does the value comparison as in the sortByID example above, only have it compare the value you want to compare instead of the ID as shown in the example. In the aforementioned post by Bill Richards, he was sorting by the innerHTML of the elements and was therefore comparing that value in his sorting function.

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader