[jquery] Sort divs in jQuery based on attribute 'data-sort'?

If I have several divs:

<div data-sort='1'>div1</div>
<div data-sort='4'>div4</div>
<div data-sort='8'>div8</div>
<div data-sort='12'>div12</div>
<div data-sort='19'>div19</div>

And I dynamically create the divs:

<div data-sort='14'>div1</div>
<div data-sort='6'>div1</div>
<div data-sort='9'>div1</div>

How can I get them to just sort into the divs already loaded in order, without having to reload all of the divs?

I think that I would need to build an array of the data-sort values of all of the divs on the screen, and then see where the new divs fit in, but I am not sure if this is the best way.

The answer is


Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

You can call this function just after adding new divs.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.

_x000D_
_x000D_
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
    elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
   $('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
   <div class="imgs" data-image-id='1'>1</div>_x000D_
   <div class="imgs" data-image-id='2'>2</div>_x000D_
   <div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/ruys9ksg/


I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html


Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery-ui-sortable

jQuery UI Sortable, then write order into a database Using jQuery UI sortable with HTML tables Sort divs in jQuery based on attribute 'data-sort'? Jquery sortable 'change' event element position jQuery UI Sortable Position