I have several divs like this
<div rel="5">
  Divs content goes here
</div>
<div rel="3">
   Div 3 Here
</div>
<div rel="4">
  Div 4 Here
 </div>
 <div rel="4.5">
   Div 4.5 here
</div>
How would you use Jquery to sort the divs so that physically in the DOM they are sorted with the least rel attribute first?
e.g. 3, 4, 4.5, 5
See my fiddle: http://jsfiddle.net/6hpNz/8/
You can leverage a combination of javascript and jQuery to do this pretty easily:
Given the following HTML:
<div class="unsorted">
    <div rel="5">
      Div 5 here
    </div>
    <div rel="3">
       Div 3 Here
    </div>
     <div rel="4.5">
       Div 4.5 here
    </div>
    <div rel="4">
      Div 4 Here
     </div> </div>
<div class="sorted"></div>
This script will give you the desired output:
$(document).ready(function () {
    var sortedDivs = $(".unsorted").find("div").toArray().sort(sorter);
    $.each(sortedDivs, function (index, value) {
        $(".sorted").append(value);
    });
});
function sorter(a, b) {
    return a.getAttribute('rel') - b.getAttribute('rel');
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With