sort unordered list javascript code example

Example: html reorder list aaccording

function sortMeBy(arg, sel, elem, order) {
        var $selector = $(sel),
        $element = $selector.children(elem);
        $element.sort(function(a, b) {
                var an = parseInt(a.getAttribute(arg)),
                bn = parseInt(b.getAttribute(arg));
                if (order == "asc") {
                        if (an > bn)
                        return 1;
                        if (an < bn)
                        return -1;
                } else if (order == "desc") {
                        if (an < bn)
                        return 1;
                        if (an > bn)
                        return -1;
                }
                return 0;
        });
        $element.detach().appendTo($selector);
}
/* arg : The data-filter to parse for sorting. In our case it would be “data-category”
sel : This will be the parent selector that contains the data filter. In our case it is the class “search-results”
elem : This further narrows down the child elements within the parent selector, which is just a “li” in this case
order : This specifies the sort order. “asc” or “desc” would either be acceptable *\

Tags:

Html Example