Tuesday, April 9, 2013

simply sorting child elements via their content

On stackoverflow article, Jquery - sort DIV's by innerHTML of children, Shawn Chin offers a simple, configurable, plug-in-free way of sorting the children of a parent div:

function sortUsingNestedText(parent, childSelector, keySelector) {
    var items = parent.children(childSelector).sort(function(a, b) {
        var vA = $(keySelector, a).text();
        var vB = $(keySelector, b).text();
        return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
    });
    parent.append(items);
}


The code then called be called with something like:
sortUsingNestedText($('#sortThis'), "div", "span.price");

That's pretty clever! I didn't realize you could .append() a child to its own parent to put it at the end.

I had to make a variant of it because I wanted all the divs that had the class "bonus" to be sorted before everything else in the list. (I decided just to write a special case rather than generalize the issue, but I could see making some kind of comparator function as an argument, but anyway this is an example of how the logic has to work, roughly)

function sortUsingNestedTextBonusFirst(parent, childSelector, keySelector) {
    var items = parent.children(childSelector).sort(function(a, b) {
        var panelA = $(a);
        var panelB = $(b);
        if(panelA.hasClass("bonus") && ! panelB.hasClass("bonus")) return -1;
        if(! panelA.hasClass("bonus") && panelB.hasClass("bonus")) return 1;
        var vA = panelA.find(keySelector).text();
        var vB = panelB.find(keySelector).text();
        return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
    });
    parent.append(items);
}

No comments:

Post a Comment