getButterfly Logo getButterfly code wrangling since 2005

Sometimes, you need to sort div elements based on a custom order parameter. The parameter may come from a database or from user input and you need to resort the elements when displaying them.

Let’s suppose we have the following HTML structure:

<div class="grid">
    <div class="grid-box" data-order="2">
        <!-- content here -->

    <div class="grid-box" data-order="1">
        <!-- content here -->

    <div class="grid-box" data-order="3">
        <!-- content here -->

Notice how the display order is incorrect now. Using jQuery, you can easily reorder everything on runtime:

$(document).ready(function() {
    var $wrapper = $('.grid');

    $wrapper.find('.grid-box').sort(function(a, b) {
        return +a.dataset.order - +b.dataset.order;


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.

Leave a reply