按ID分类元素数组

时间:2014-12-23 14:07:34

标签: javascript jquery arrays

我试图根据他们的ID对DOM元素数组进行排序。通过获取具有给定类的所有元素来填充数组:

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

如何通过ID完成排序?

2 个答案:

答案 0 :(得分:2)

您必须对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);

答案 1 :(得分:0)

rowList = rowList.sort(function(a, b) {
    return a.id.localeCompare(b.id);
});