Order Divs Based on an attribute value in Jquery

Go To StackoverFlow.com

4

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

2012-04-04 23:51
by Talon
Well, what did you try? what do you have so far - gdoron 2012-04-04 23:57
A quick Google search yields several plugins that do this: https://www.google.com/search?q=jquery+element+sor - inkedmn 2012-04-04 23:58


12

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');
};
2012-04-05 02:48
by David Peden
Great solution. I was able to implement this in about 30 seconds to sort some horizontal bar charts. Thanks - Jon 2013-02-11 15:49
Great solution. Thank you - Mino 2018-01-16 23:45


1

I'm sure there is a much more efficient way, but here is my answer anyway:

HTML:

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

jQuery:

var array = new Array();

$('div').each(function(){   
    array.push($(this).attr('rel'));
});

array = array.sort();

var reordedDivs = "";

$.each(array, function(i, obj1){

    $('div').each(function(j, obj2) {

        if ($(obj2).attr('rel') == obj1) {

            var divContent = $(obj2).html();
            var rel = obj1;

         reordedDivs += "<div rel='" + rel + "'>" + divContent + "</div>";

        }

            });  
});

$('body').html(reordedDivs);

Fiddle: http://jsfiddle.net/F6csV/17/

2012-04-05 02:10
by kmb64


0

You can select elements with a DOM method, convert DOM list to Array, and then use Array.sort().

2012-04-04 23:57
by Marat Tanalin
Ads