3

I’m trying to reorder divs on the base of certain values they contain. My code is the following

HTML

<div id="content_id_1">
  <ul>
    <li> some text, not important for the reordering but it must move with it's parent div</li>
    <li> some text, not important for the reordering but it must move with it's parent div</li>
    <li>
      <div class=‘date--2011-11-11’>2011-11-11’< /div> 
    </li>
  </ul>
</div>
<div id="content_id_2">
  <ul>
    <li> some text, not important for the reordering but it must move with it's parent div</li>
    <li> some text, not important for the reordering but it must move with it's parent div</li>
    <li>
      <div class=‘date--2011-10-10’>2011-10-10’< /div> 
    </li>
  </ul>
</div>

And so on…

On changing the filter called #data_filter, I would like the main div (those with content_id_something) and their whole content to be reordered by the date value... I tried to adapt the following example (http://stackoverflow.com/questions/2501789/jquery-sort-divs-according-to-content-of-different-sub-divs), but I am a bit lost... JQuery :

$("#data_filter").change(function(){
    function sortDateASC(a, b){
        return $(a).find(div[class^=date--])  > $(b).find(div[class^=date--])  ? 1 : -1;
   };
$(div[class^=date--]) .each(function(){
    $(this).parent().parent().parent().sort(sortDateASC);
   }); 
}) ;

Thank you very much for your help!

Raphael
  • 1,709
  • 2
  • 17
  • 27

2 Answers2

1

something like this:

$("#data_filter").change(function(){
  function sortDateASC(a, b){
    var keya = new Date($(a).find('div[class^="date--"]').text().replace("'","")).getTime();
    var keyb = new Date($(b).find('div[class^="date--"]').text().replace("'","")).getTime();
    return keya > keyb ? 1 : keya < keyb ? -1 : 0;
  }
  $('div[class^="date--"]') .each(function(){
    $(this).closest("#listparent").children().sort(sortDateASC).appendTo("#listparent");
  }); 
});

where the list is wrapped in an element with an id of listparent

Edit: here's a fiddle: http://jsfiddle.net/EUkPb/

Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

you can only compare values, not jquery objects. so you could try:

return $(a).find(div[class^=date--]).attr('class')  > $(b).find(div[class^=date--]).attr('class') ? 1 : -1;

not sure if it works though.

Andy
  • 29,707
  • 9
  • 41
  • 58