'get data attribute from array

i am tring to modify this sortlist to sort by most recent date from a data attribute.

function sortList(ul) {
   var ul = document.getElementById(ul);
   Array.from(ul.getElementsByTagName("div"))
   .sort((a, b) => a.textContent.localeCompare(b.textContent))
   .forEach(div => ul.appendChild(div));
}

and here is the html

 <div class="grid customer-card-cnt" id="customerlist">
     <div class="col col-sm col-4" data-date="2014-05-10"></div>
     <div class="col col-sm col-4" data-date="2022-05-10"></div>
     <div class="col col-sm col-4" data-date="2021-05-10"></div>
</div>


Solution 1:[1]

It seems like you're sorting using the wrong property i.e. textContent instead of the value of the data-date attribute. I've modified your example below to show the correct sort function.

function sortList(ul) {
  var ul = document.getElementById(ul);
  Array.from(ul.getElementsByTagName("div"))
    .sort((a, b) => b.dataset.date.localeCompare(a.dataset.date))
    .forEach((div) => ul.appendChild(div));
}

This should produce the following html:

 <div class="grid customer-card-cnt" id="customerlist">
     <div class="col col-sm col-4" data-date="2022-05-10"></div>
     <div class="col col-sm col-4" data-date="2021-05-10"></div>
     <div class="col col-sm col-4" data-date="2014-05-10"></div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 christiandrey