-3

I have 2 divs

<div class="row events-list-section employee-hour-detail-section 11-28-2017">
</div>
<div class="row events-list-section employee-hour-detail-section 11-27-2017">
</div>

The divs have common classes employee-hour-detail-section and date as extra class.

I want to sort these divs according to date. How can I achieve that? I want the output to be sorted date wise.

<div class="row events-list-section employee-hour-detail-section 11-27-2017">
</div>
<div class="row events-list-section employee-hour-detail-section 11-28-2017">
</div>
6
  • Yes you can, see the duplicate I linked to. Note that for this to work the individual classes within the class attributes must be in the exact same order on the different elements. Commented Nov 27, 2017 at 10:42
  • My divs are not integers. they are dates. Commented Nov 27, 2017 at 10:46
  • what about 12-31-2017 and 01-01-2018? Commented Nov 27, 2017 at 10:48
  • 1
    Then put the year first. Commented Nov 27, 2017 at 10:48
  • The thing is that I do not have the access of that code. But that's why I want to sort is according to the date as in the given format. Is that possible or not? Please open my question since this is an issue for me. Commented Nov 27, 2017 at 10:50

1 Answer 1

1

To make this work you need to know the exact date value. Doing this in a class is possible, but it will be brittle and ugly code.

Instead I'd suggest putting the date in to a data variable in your HTML which you can then sort by comparing the values in a sort() handler, like this:

$('.events-list-section').sort(function(a, b) {
  var aDate = $(a).data('date'), bDate = $(b).data('date');
  return new Date(aDate) - new Date(bDate);
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row events-list-section employee-hour-detail-section" data-date="11-28-2017">11-28-2017</div>
<div class="row events-list-section employee-hour-detail-section" data-date="12-31-2017">12-31-2017</div>
<div class="row events-list-section employee-hour-detail-section" data-date="01-01-2018">01-01-2018</div>
<div class="row events-list-section employee-hour-detail-section" data-date="11-27-2017">11-27-2017</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou so much. Just a last question. This doesn't seem to work on safari. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.