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

标签 javascript html sorting dom

我想使用 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())
);

关于javascript - 如何使用 JavaScript 控制台对现有 DOM 元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38814096/

相关文章:

html - 从YouTube删除单词 'views'

html - Flickr 如何防止人们从网站下载图片?

java - 对对象数组列表进行排序问题

javascript - 使用 reverse() javascript 求和两个最高值

javascript - HTML5站点在silk浏览器中进入全屏模式还是在加载url后在silk浏览器中隐藏地址栏?

javascript - 用 RegEx 和 jQuery 替换文本

javascript - 无法在 LightSwitch HTML 中使用 Syncfusion JavaScript 组件

javascript - 替换 STYLE 内容 javascript HTML

html - 使用用户代理风格

mysql - ORDER BY CASE 行为不正确