I have a pretty weird problem with sorting in JavaScript. I’ve wandered into this wonderfully and horribly confusing world of sorting, and was wondering if you guys could help me out:
Basically, I’m trying to mimic the tabindex HTML attribute, which basically changes the order of ‘tabbing’ through the page: Elements with a tabindex are first, with the smallest positive number first, going down, and the elements without tabindex are last in an unchanged order. So, it’s like this:
tabindex=1, tabindex=2, tabindex=5, tabindex=5000, no tabindex, no tabindex, no tabindex, etc…
I’m trying to get this working. In Chrome it doesn’t work because of (I think, at least) the sorting algorithm it uses compared to all other major browsers.
What’s returned in Chrome is sporadic and weird, with one element completely out of order and other elements that used to be at the top instead at the bottom.
In all other browsers, it works (except the tabindex’d elements are in a reversed order, but that’s really easy to fix, that I was planning on doing after I got this working). This is using the following code:
selectElements.sort(function(a,b){
return b.getAttribute('tabindex')-a.getAttribute('tabindex');
});
I believe the problem may stem from the fact that elements without getAttribute are returned null, but what do I know… 😛
Let me know what you guys would do to make this work… Thanks!
Improving on the answer from @3dgoo, the sort method should check for equality first: