如何使用javascript控制台对现有DOM元素进行排序

How to sort existing DOM elements using a javascript console?

本文关键字:元素 DOM 排序 何使用 javascript 控制台      更新时间:2023-09-26

我想使用firefox中内置的javascript控制台对网页中的一些表行进行排序。网站本身不提供按字母排序,但数据库很大,我需要更快地找到东西。

结构如下:

<table id="entries">
    <tr>
        <td>
            <img />
            DATA
        </td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>...</tr>
    ...
</table>

所以最后我想重新排序那些tr-元素,按字母顺序排序DATA

(使用Firefox搜索不起作用,因为它不会滚动到单词的位置,我需要找到多个同名的项目。(

你的问题很一般,答案也是。

var table = document.querySelector("table");
//append the ordered nodes, wrapped in a DocumentFragment
//this will be the last task that will be run, 
//although it's the first command here
table.appendChild(
    //get the rows you want to sort and convert the NodeList into an Array
    Array.from(table.querySelectorAll("tr"))
        //fetch the data you want to sort by.
        .map(row => {
            //return an intermediate-representation that associates
            //your row with the (now cached) data you want to sort by.
            //fetching this data in the sort-function would be way more expensive
            return {
                target: row,
                value: row.querySelector("td").textContent
            }
        });
        //sort
        .sort((a,b) => a.value.localeCompare( b.value )) 
        //concat the rows into a document-fragment
        .reduce((frag, data) => {
            frag.appendChild( data.target );
            return frag;
        }, document.createDocumentFragment())
);

我做了一些不同的事情,但我真的很喜欢@Thomas的代码,所以我只想根据他的解决方案生成一个通用的tableSorter函数。作为对表头元素单击事件的回调,这可能非常有用。

此函数接受三个参数;

  1. 表对象
  2. 要排序的单元格(列(索引
  3. 如果true上升,否则下降

function tableSorter(table,cellIndex,order){ // table object, cell index and order passed as arguments
  var frag = [...table.rows].map(row              => ({tr: row, data: row.cells[cellIndex].textContent.trim()}))
                            .sort((a,b)           => order ? a.data.localeCompare(b.data) : b.data.localeCompare(a.data))
                            .reduce((frag,sorted) => (frag.appendChild(sorted.tr), frag),document.createDocumentFragment());
  window.requestAnimationFrame(table.appendChild.bind(table,frag));
  return table;
}
var myTable = document.getElementById("entries");
tableSorter(myTable,0,true);
<table id="entries">
  <tr>
    <td>
      <img /> XDATA
    </td>
    <td>d</td>
    <td>w</td>
    <td>h</td>
  </tr>
  <tr>
    <td>
      <img /> ADATA
    </td>
    <td>p</td>
    <td>e</td>
    <td>q</td>
  </tr>
  <tr>
    <td>
      <img /> FDATA
    </td>
    <td>a</td>
    <td>b</td>
    <td>x</td>
  </tr>
</table>