Showing posts from October, 2009

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 > ? 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 …