Paedow Paedow - 3 months ago 9
HTML Question

How to sort existing DOM elements using a javascript console?

I want to sort some table rows from a webpage using the built-in javascript console in firefox. The website itself doesn't offer alphabetical sorting, but the database is big and i need to find things faster.

The structure is like this:

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


So finally i want to reorder those
tr
-elements sorting DATA alphabetically

(Using the Firefox Search doesn't work, because it won't scroll to the position of the word and i need to find multiple items with the same name.)

Answer

Your question is quite generic, so will be the answer.

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())
);
Comments