<button id="sort" type="button">Sort</button>
<br><br>
<div id="body">
<div class="listing-item" data-event-date="2017-05-02">2017-05-02</div>
<div class="listing-item" data-event-date="2018-01-07">2018-01-07</div>
<div class="listing-item" data-event-date="2017-06-05">2017-06-05</div>
<div class="listing-item" data-event-date="2018-01-03">2018-01-03</div>
<div class="listing-item" data-event-date="2017-08-08">2017-08-08</div>
</div>
const items = [...document.querySelectorAll('.listing-item')];
function compare(a, b) {
const aData = new Date($(a).data('event-date'));
const bData = new Date($(b).data('event-date'));
if (aData < bData) {
return -1;
}
if (aData > bData) {
return 1;
}
return 0;
}
$('#sort').on('click', () => {
items.sort(compare);
$('#body').empty();
items.forEach(item => {
$('#body').append(item);
});
});