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 from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2