Order divs based on dates inside a span element
I have 4 divs which I would like to order dynamically based on the date inside the span tag. I would like it to appear from newest to oldest. What's the best way to achieve this using JQuery?
<div class="mydivs">Some description goes here <span>05/03/09</span></div>
<div class="mydivs">Some description goes here <span>01/15/11</span></div>
<div class="mydivs">Some description goes here <span>1开发者_开发问答2/25/07</span></div>
<div class="mydivs">Some description goes here <span>09/25/11</span></div>
See example of the following here →
var amd = [],
tDate, tElem;
$('.mydivs').each(function(i, elem) {
var aDate = $(this).children('span').text().split('/');
$(this).data('date', aDate[2] + aDate[1] + aDate[0]);
});
amd = $('.mydivs').map(function() {
return $(this).data('date');
}).get();
amd.sort();
while (amd.length) {
tDate = amd.pop();
tElem = $('.mydivs').filter(function() {
return $(this).data('date') == tDate;
}).detach();
$('#wrapper').append(tElem);
}
That was fun!
There's this great plugin for Sorting Elements with jQuery.
Or you can do it by hand. Doing it by hand would involve something like this:
var toSort = new Array();
$('div.mydivs').each(function (divIndex, divElement) {
toSort[$(divElement).first('span').text()] = $(divElement.html());
});
With that, you'd have a hashtable of all your divs and you can sort the keys, delete the original divs and re-append them in the right order.
精彩评论