Volatil3
Volatil3

Reputation: 14998

Sorting LI elements w.r.t Datetime attribute

I have the following snippet for li tag:

tl = '<li>';
    tl+= '<time class="cbp_tmtime" datetime="2013-04-10 18:30"><span>04/10/13</span> <span>18:30</span></time>';
    tl+= '<div class="cbp_tmlabel">';
    tl+= '<p>TL Content Goes here</p>';
    tl+= '</div>';
    tl+= '</li>';

As you can see there's a time tag. Is it possible to use jQuery to sort <ul> based w.r.t datetime attribute?

Upvotes: 0

Views: 347

Answers (2)

adrenalin
adrenalin

Reputation: 1658

Sure it is.

You can write a sort for them: How to define custom sort function in javascript?

Here is a fiddle: http://jsfiddle.net/58eyg7ds/1/ and the code used to create a custom sort for jQuery:

$.fn.sortMyData = function() {
  var elements = $(this).find('> *');

  // Create an array for the content
  var arr = [];

  for (var i = 0; i < elements.length; i++) {
    arr.push(elements.eq(i));
  }

  arr.sort(function(a, b) {
      var dateA = new Date(a.attr('datetime').replace(/([0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}) /, '$1T'))
    var dateB = new Date(b.attr('datetime').replace(/([0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}) /, '$1T'))

    if (dateA < dateB) {
      return -1;
    }

    if (dateA > dateB) {
      return 1;
    }

    return 0;
  });

  for (i = 0; i < arr.length; i++) {
    $(this).append(arr[i]);
  }
}

$('ul').sortMyData();

Upvotes: 1

user4176466
user4176466

Reputation: 200

Adapting the code from this question, you should be able to do something like this.

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]); //     months are 0-based
}

var elems = $.makeArray($(".dateDiv"));
elems.sort(function(a, b) {
    // Ascending order
    return parseDate( $(a).attr("datetime") ) > parseDate( $(b).attr("datetime") );
});
$("#D").html(elems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="D">
    <div class="dateDiv" datetime="2012-04-15 10:25:45">2012-04-15 10:25:45</div>
    <div class="dateDiv" datetime="2012-04-10 19:41:08">2012-04-10 19:41:08</div>
    <div class="dateDiv" datetime="2012-04-20 07:00:10">2012-04-20 07:00:10</div>
    <div class="dateDiv" datetime="2012-04-12 16:45:50">2012-04-12 16:45:50</div>
</div>

Upvotes: 0

Related Questions