I have multiple div elements with data-timestamp attribute
What I want to do is sort these divs by data-timestamp (newer to older).
I decided to loop through elements and swap their positions. If an element's next sibling has a newer data-timestamp than the current element, then next sibling inserts before current.
$.each($('.sorted-chat-item'), function( i, value ) {
//current element's timestamp
var date = new Date($(value).attr('data-timestamp'));
//all elements
var list = $('.sorted-chat-item');
for(var j = i+1; j < list.length; j++){
//next element's timestamp
var nextDate = new Date($(list[j]).attr('data-timestamp'));
if(date < nextDate){
$(list[j]).insertBefore( $(list[i]) );
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='sorted-chat-item' data-timestamp="2017-09-01 18:09:22">2017-09-01 18:09:22</div>
<div class='sorted-chat-item' data-timestamp="2017-09-01 18:01:27">2017-09-01 18:01:27</div>
<div class='sorted-chat-item' data-timestamp="2017-09-01 18:31:36">2017-09-01 18:31:36</div>
but it doesn't sort correctly. Any idea, what am I doing wrong?
"in the last div to close thedata-timestampattribute.$().find('.header h3').text()to$().data("timestamp")