Hello, the question is how to sort the table by ID in ascending / descending. I really need your help.

<TR style="font-weight:700; background: linear-gradient(to top, #e0edf5, #c2dbe7);"> <TD>Номер</TD> /*это название колонки с id*/ <TD>Название</TD> <TD>БИН/ИНН</TD> <TD>Адрес</TD> <TD width="150">Редактирование</TD> <TD width="150">Удалить</TD> </TR> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>&nbsp;[LL_REPTAG=SEQ /]</TD> /*эта колонка я так понимаю и есть колонка с прописанными id*/ <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> 

    2 answers 2

    If there is no raw data (native JS objects) by which a table can be built, then there are two ways out:

    • Actually, first create native JS objects from the table, then delete all TR DOM elements and rebuild the table using document.createElement\appendChild\insertChild .
    • Or you can remove the TR elements from the table and put them in an array. Then sort the array with the standard sort function in the JS qsort , and then embed the items back into the DOM.

      Click on the number :

       document.querySelector('thead th:first-child').onclick = e => { const tbody = document.querySelector('tbody'); const rows = [...document.querySelectorAll('tbody tr')]; rows.sort((tr1, tr2) => { if (parseInt(tr1.querySelector('td').innerText) < parseInt(tr2.querySelector('td').innerText)) { return -1; } else { return 1; } }); tbody.innerHTML = ''; rows.forEach(row => tbody.appendChild(row)); } 
       <table> <thead> <TR style="font-weight:700; background: linear-gradient(to top, #e0edf5, #c2dbe7);"> <th>Номер</th> <th>Название</th> <th>БИН/ИНН</th> <th>Адрес</th> <th width="150">Редактирование</th> <th width="150">Удалить</th> </TR> </thead> <tbody> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>4</TD> <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>&nbsp;1</TD> <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>&nbsp;3</TD> <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>&nbsp;2</TD> <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> <TR VALIGN="CENTER" NOWRAP ALIGN="LEFT" BGCOLOR="White"> <TD>5</TD> <TD>&nbsp;[LL_REPTAG=NAME /]</TD> <TD>&nbsp;[LL_REPTAG=BIN /]</TD> <TD>&nbsp;[LL_REPTAG=Address /]</TD> <TD align="center"> </TD> </TR> <tbody> </table> 

      • thank! but unfortunately it doesn't work (I can't change the source code - Daria Shmatova