getButterfly Logo getButterfly

My latest client project had a huge list of elements which needed to be sorted on the fly based on several data attributes. I approached this by using jQuery and HTML5 data-attribute="my-value".

jQuery Element Sorting

First, we need to create a simple list:

<ul class="sort-list">
    <li data-score="1" data-price="123">€ 123 (Score: 1)</li>
    <li data-score="5" data-price="67">€ 67 (Score: 2)</li>
    <li data-score="4" data-price="111">€ 111 (Score: 3)</li>
    <li data-score="3" data-price="4">€ 4 (Score: 4)</li>
    <li data-score="2" data-price="200">€ 200 (Score: 5)</li>

Note the data-score and data-price attributes. You can add as many as you want, provided they have a numerical value.

Second, we need to create the sorting links/buttons:

<a href="#" class="sort1">Sort by price (descending)</a> 
<a href="#" class="sort2">Sort by price (ascending)</a> 
<a href="#" class="sort3">Sort by score (descending)</a> 
<a href="#" class="sort4">Sort by score (ascending)</a>

The last step is to create the jQuery function:

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;


$(document).on('click', '.sort1', function() {
    sortMeBy('data-price', 'ul.sort-list', 'li', 'desc');
$(document).on('click', '.sort2', function() {
    sortMeBy('data-price', 'ul.sort-list', 'li', 'asc');
$(document).on('click', '.sort3', function() {
    sortMeBy('data-score', 'ul.sort-list', 'li', 'desc');
$(document).on('click', '.sort4', function() {
    sortMeBy('data-score', 'ul.sort-list', 'li', 'asc');

Notice the code above has one function and four click triggers. Add more triggers based on how many sorting buttons you have. Make sure to match the element class and the sorting order (ascending or descending)

See our demo on Codepen!

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

2 thoughts on “jQuery – Sort elements based on data attributes

  1. I’ve had to write similar code to this recently and it’s become a bit hard to handle yours seems to be alot more flexible and more or less plug and go, thank you for sharing it!

Leave a reply