0

I'm trying to sort an array of DOM elements based on their ID. The array is populated by getting all elements with a given class:

var rowsList = document.getElementsByClassName("employee_grid_rows");
rowsList.sort(); //??

How do I get the sorting done by ID?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

2 Answers2

2

You have to sort the HTMLCollection

var rowsList = document.getElementsByClassName("employee_grid_rows");
console.log(rowsList);

var arr = Array.prototype.slice.call( rowsList );
rowsList = arr.sort(function(a, b) {
  //Comparing for strings instead of numbers
  return a.id.localeCompare(b.id);
});

console.log(rowsList);
Jeremy Friesen
  • 383
  • 1
  • 3
  • 13
sbaglieri
  • 319
  • 2
  • 10
0
rowList = rowList.sort(function(a, b) {
    return a.id.localeCompare(b.id);
});
Jeremy Friesen
  • 383
  • 1
  • 3
  • 13