views:

41

answers:

1

Hi, is it possible to sort div by using the data function?

html

<div id="gp_21" class="line">one</div>
<div id="gp_35" class="line">two</div>
<div id="gp_11" class="line">three</div>
<div id="gp_29" class="line">four</div>

<hr />

<div id="check"></div>

js

$(document).ready(function rt() {

    $('#gp_21').data("rtt", { age: '251351' });
    $('#gp_35').data("rtt", { age: '25131151' });
    $('#gp_11').data("rtt", { age: '251' });
    $('#gp_29').data("rtt", { age: '25131148' });

check();

});


function check()
{

    $('.line').each(function() {

     age = $('#'+this.id+'').data("rtt").age;

     $('#check').append('-> '+age+' - '+this.id+'<br />');


    });

}

working example -> http://www.jsfiddle.net/V9Euk/265/

Thanks in advance! Peter

+1  A: 

hi See this http://www.jsfiddle.net/V9Euk/268/

function check()
{
    var ages= [];
    var ids = []
    $('.line').each(function() {

         ages[ages.length] = $('#'+this.id+'').data("rtt").age;           
         ids[ids.length] = this.id;
    });    
    ages.sort(sortByAge);
    $(ages).each(function(i, v) {             
        for(key in ids)
        {
            if($("#"+ids[key]).data("rtt").age == v)
            {
                 $('#check').append('-> '+v+' - '+ids[key]+'<br />');   
            }
        }

    });

}
function sortByAge(a, b)
{
      return a-b;
}

Hi I updated my answer for appending sorted divs.

Ayaz Alavi