This question already has answers here:
How to sort DOM elements while selecting in jQuery?
                            
                                (4个答案)
                            
                    
                5年前关闭。
        

    

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

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


如何通过ID进行排序?

最佳答案

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

09-17 07:16