Sort child elements based on date using jQuery

This code can be used for sorting the child elements based on the date. In this example, I have added a data attribute to each child element and this data attribute has date values in dd-mm-yyyy format.  This code will sort the child elements in Ascending order of the date values.

jQuery Code

  function sortDateAsc(a, b) {
		var date_a  = $(a).find(".date").data("date").split('-');
		date_a = new Date(date_a[2], date_a[1] -1, date_a[0]);
		var date_b  = $(b).find(".date").data("date").split('-');
		date_b= new Date(date_b[2], date_b[1] -1, date_b[0]);
		return date_a < date_b ? 1 : -1;
	$('#boxes .box').sort(sortDateAsc).appendTo('#boxes');

HTML code

<ul id="boxes">
  <li class="box"><span class="date" data-date="02-06-2021">1</span></li>
  <li class="box"><span class="date" data-date="01-03-2021">5</span></li>
  <li class="box"><span class="date" data-date="08-04-2021">3</span></li>
  <li class="box"><span class="date" data-date="05-03-2021">4</span></li>
  <li class="box"><span class="date" data-date="17-05-2021">2</span></li>
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us