Using JavaScript to sort divs based upon content & sorting empty divs to the end

Viewed 39

The code below shows my current workings. the commented out line sorts my divs but leaves the empty divs at the top.

the 4 lines above do not make a difference

I think I'm missing something really simple here

//Group 1
    var alphabeticallyOrderedDivs7 = $('.group1').sort(function getSort(a, b) {
        if($(a).find(a).text() === "") return 1;
        if($(b).find(b).text() === "") return -1;
        if($(a).find(a).text() === $(b).find(b).text()) return 0;
        return $(a).find(a).text() < $(b).find(b).text()) ? -1 : 1;
        //return String.prototype.localeCompare.call($(a).text().toLowerCase(), $(b).text().toLowerCase());
    });
1 Answers

You can simply do this:

//Group 1
    var alphabeticallyOrderedDivs7 = $('.group1').sort(function getSort(a, b) {
        //Assuming $(a).text() and $(b).text() is the content of the div
        return $(a).text() < $(b).text() ? 1 : $(a).text() > $(b).text() ? -1 : 0;
    });
Related