Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace html dataset with variables

Hi,

I have this code to sort a html list:

 function sortList(listid){
  //some stuff
  elms.sort(function(a, b){
   if(a.dataset.age < b.dataset.age) { return minusone; }
   if(a.dataset.age > b.dataset.age) { return plusone; } 
   return 0;
  });
 }

this works fine but I want to modify it so I can use variables to work with different datasets:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 function sortList(listid,type,direction){
   //some stuff
   var typesort = 'dataset'.type;
   elms.sort(function(a, b){
     if(a.typesort < b.typesort) return minusone;
     if(a.typesort > b.typesort) return plusone;
     return 0;
    });
   }

but this is not working as expected since the sorting is all over the place. You can see it live here: http://jsfiddle.net/ocymgrL7/2/

what is the correct syntaxis to accomplish this?

Thank you.

>Solution :

If you mean to say that a has a property dataset and that property, a.dataset, has property age, you can say a.dataset.age OR you can say a.dataset[age]

// Sort the lis in descending order
elms.sort(function(a, b){
 if(a.dataset[type] < b.dataset[type]) return minusone;
 if(a.dataset[type] > b.dataset[type]) return plusone;
 return 0;
});

See reference: bracket notation

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading