Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Divs Based on an attribute value in Jquery

Tags:

jquery

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

like image 329
Talon Avatar asked Dec 12 '22 03:12

Talon


1 Answers

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');
};
like image 117
David Peden Avatar answered Dec 28 '22 21:12

David Peden