0

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?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    Your comparison function is completely wrong. It's supposed to return a number, not true/false. it returns less than 0 if `a < b`, it returns greater than 0 if `a > b`, otherwise it returns 0. – Barmar Jun 04 '16 at 10:08
  • [Your comparison function is invalid](http://stackoverflow.com/q/24080785/1048572). – Bergi Jun 04 '16 at 12:27

1 Answers1

0

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);
    });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188