Anton Kihlström Anton Kihlström - 6 months ago 9
jQuery Question

How to sort items above 99?

I got a bit of JavaScript that sort divs on my website depending on whats the content in a span tag inside it.

It looks like this:

$(window).load(function(){
var $divs = $("div.box");
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("span").text() < $(b).find("span").text();
});
$("#container").html(numericallyOrderedDivs);
});
});


The only problem I got with it that when the numbers inside the Span tag gets above 99 it dosent order anymore, with other words it only orders numbers 0-99. is there any way I can get it order all numbers depending on how big they are?

Answer

Get the difference of numbers and return it. There is no need to parse the string, since subtraction(-) automatically converts it to number.

$(window).load(function(){
    var $divs = $("div.box");        
    $('#numBnt').on('click', function () {

        var numericallyOrderedDivs = $divs.sort(function (a, b) {
            return $(b).find("span").text() - $(a).find("span").text();
        });

        $("#container").html(numericallyOrderedDivs);
    });
});