jQuery   

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

jQuery(document).ready(function($){	
  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>
<ul>
Need Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us

Got an idea? We'll turn it into reality.

Tell us what you're building, what's broken, or what numbers need to move. We'll come back within one business day with a short plan — no long decks, no sales calls without purpose.

Response time: First reply within 1 business day on 100% of messages.
Transparent scope: Fixed proposals with weekly check-ins & live task tracking.
Ship-ready builds: Every engagement leaves behind documented, transferable work.
Long-term partners: Ongoing retainers for support, SEO, ads, and content.