user1225840
user1225840

Reputation: 25

sort() function in IE

So this code doesnt seem to work with IE, I have not found anything that says it shouldn't. What am I doing wrong?

 ​<ul id="cars">
    <li id="2">Ford</li>
    <li id="1">Volvo</li>
    <li id="3">Fiat</li>
    </ul>



var list = $('#cars').children('li');
    list.sort(function(a,b){
        return parseInt(a.id) < parseInt(b.id);
    });
    $('#cars').append(list);

Upvotes: 2

Views: 324

Answers (2)

Blazemonger
Blazemonger

Reputation: 92963

It's considered incorrect in HTML4 to start IDs with numbers. This rarely causes problems in browsers, but it's also easily avoided.

I replaced your IDs with data- attributes, which are automatically extracted by the .data() method in jQuery and converted into numbers, eliminating the need for parseInt.

HTML:

<ul id="cars">
    <li data-val="2">Ford</li>
    <li data-val="1">Volvo</li>
    <li data-val="3">Fiat</li>
</ul>

JS:

$('#cars').children('li').sort(function(a, b) {
    return $(a).data('val')-$(b).data('val');
}).appendTo('#cars');​​​​​
​

Fiddle: http://jsfiddle.net/qaytJ/1/

data- attributes are useful whenever you want to attach arbitrary data to HTML elements, and it's more "correct", or at least more appropriate, than forcing id or class to do a job it wasn't intended to do. Use them often.

Upvotes: 2

Matt Greer
Matt Greer

Reputation: 62057

The sort function you pass in should return either a number less than zero (a comes before b), 0 (a and b are equivalent) or greater than 0 (a comes after b).

If you just do this, it should work:

return parseInt(a.id) - parseInt(b.id);

also can't hurt to pass in the radix argument to parseInt, it's a bit safer:

return parseInt(a.id, 10) - parseInt(b.id, 10);

Upvotes: 7

Related Questions