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

TaylorMac picture TaylorMac · May 26, 2011 · Viewed 104.9k times · Source

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.

Answer

Jayantha Lal Sirisena picture Jayantha Lal Sirisena · May 26, 2011

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);