wawanopoulos
wawanopoulos

Reputation: 9804

Sort li elements based on a timestamp value

I have a list of li elements like that:

<li>
   <div class="historyDateBloc">
      <span class="dateTop"></span>
      <span class="dateBottom"></span>
      <span class="hiddenDate">1481727905</span>
      <p class="historyDateText">14 Dec <br>2016</p>
   </div>
   <p class="historyMainText">Equipment shipped</p>
   <p class="historySubText">Subscription equipment shipped under cso reference 0000RPO205</p>
</li>

I would like to sort from the most recent to the oldest elements the list in UI based on hiddenDate class value. How can I do that using jQuery ?

Upvotes: 0

Views: 607

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Use sort() method to sort the collection and after sorting updating it to the DOM append back using appendTo() method.

// get all li elements
$('ul li').sort(functio(a, b){
  // get difference between the content of hiddenDate element
  // where define the context as second argument inorder to get element within it
  return $('.hiddenDate', b).text() - $('.hiddenDate', a).text();
  // append back to the `ul` for updating the order
}).appendTo('ul')

Upvotes: 4

Quentin Roger
Quentin Roger

Reputation: 6538

You can do something like this :

$("li").sort(function(a, b) {
  return new Date($(a).find(".hiddenDate")) > new Date($(b).find(".hiddenDate"));
}).each(function() {
  $("ul").prepend(this);
})

https://jsfiddle.net/e17wq0am/

Upvotes: 2

Related Questions