0

I would need your help, I have a long list similar to the following:

<div id="works">
<div class="item" data-date="20160312">Item2</div>
<div class="item" data-date="20170227">Item5</div>
<div class="item" data-date="20051201">Item1</div>
<div class="item" data-date="20010515">Item3</div>
<div class="item" data-date="20100418">Item4</div>
….
</div>

I use the following method jquery sort list based on data attribute value to sort the items by date, categories ... but I would need to save the initial order before sorting. The ideal would be, for example, to create a function that would add a "data-origin" like this:

<div id="works">
<div class="item" data-origin="1" data-date="20160312">Item2</div>
<div class="item" data-origin="2" data-date="20170227">Item5</div>
<div class="item" data-origin="3" data-date="20051201">Item1</div>
<div class="item" data-origin="4" data-date="20010515">Item3</div>
<div class="item" data-origin="5" data-date="20100418">Item4</div>
….
</div>

Do you have a solution ? (I also use infinitescroll which loads the continuation of the lite, it would also be necessary that I could add this "data-origin" to the new elements) Thank you very much !

  • Why no jQuery tag if you already use a jQuery solution for sorting? With jQuery that's easily done with an [`.each()`](https://api.jquery.com/each/) and [`.data()`](https://api.jquery.com/data/) -> [jQuery Learning Center](https://learn.jquery.com/) – Andreas Jul 31 '17 at 17:18
  • Without jQuery: [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) + [`NodeList.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach) + [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) – Andreas Jul 31 '17 at 17:22

1 Answers1

0

$('.item').each(function(index){ $(this).data('origin-order', index) })

$('.item').each(function(index){ console.log($(this).data('origin-order')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="works">
<div class="item" data-date="20160312">Item2</div>
<div class="item" data-date="20170227">Item5</div>
<div class="item" data-date="20051201">Item1</div>
<div class="item" data-date="20010515">Item3</div>
<div class="item" data-date="20100418">Item4</div>
</div>
Maxim Kuzmin
  • 2,574
  • 19
  • 24