I’m trying to sort div‘s by content date on a span when the page load… What I’ve got is sorting. But not by date.
Here is my code snippet:
function sortDescending(a, b) {
var date1 = $(a).find("span").text();
date1 = date1.split('/');
date1 = new Date(date1[2], date1[1] - 1, date1[0]);
var date2 = $(b).find("span").text();
date2 = date2.split('/');
date2 = new Date(date2[2], date2[1] - 1, date2[0]);
return date1 < date2 ? 1 : -1;
};
$(document).ready(function() {
$('#container .element').sort(sortDescending).appendTo('#container');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="element">
<p class="title">TEST 03</p>
<span>01/2010</span>
</div>
<div class="element">
<p class="title">TEST 01</p>
<span>01/2012</span>
</div>
<div class="element">
<p class="title">TEST 04</p>
<span>01/2009</span>
</div>
<div class="element">
<p class="title">TEST 02</p>
<span>01/2011</span>
</div>
</div>
I know I need a function to figure out the content is a date. Just don’t know how…
The
<span>text appears to only have mm/yyyy format, whereas your date constructors are expecting 3 elements in the resulting array.You need to change the Date constructor slightly: