Home > OS >  get data attribute from array
get data attribute from array

Time:03-11

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  id="customerlist">
     <div  data-date="2014-05-10"></div>
     <div  data-date="2022-05-10"></div>
     <div  data-date="2021-05-10"></div>
</div>

CodePudding user response:

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  id="customerlist">
     <div  data-date="2022-05-10"></div>
     <div  data-date="2021-05-10"></div>
     <div  data-date="2014-05-10"></div>
</div>
  • Related