skip to Main Content

I am trying to sort the <td>‘s inside a <tr> based on the text content.

sortedCells = Array.from(tr.cells).sort((a,b) => b.textContent - a.textContent);
const cellsLength = tr.cells.length;
for(i = 0; i < cellsLength; i++) {
  const cell = tr.cells[i];
  tr.replaceChild(sortedCells[i], cell);
}

When this code is executed, it will shorten the tr.cells by one, so in one of the replaceChild() calls, something goes wrong, as a result, i will get a shorter <tr> i cant figure out why.

2

Answers


  1. I made a little modification in the javascript which works fine for me. Try this and let me know if you any other issue

    const tr = document.querySelector('tr'); 
    const sortedCells = Array.from(tr.cells).sort((a, b) => {
      return b.textContent.localeCompare(a.textContent);
    });
    
    const cellsLength = tr.cells.length;
    for (let i = cellsLength - 1; i >= 0; i--) {
      const cell = tr.cells[i];
      tr.replaceChild(sortedCells[i], cell);
    }
    
    Login or Signup to reply.
  2. const tr = document.querySelector('tr');
    const sortedCells = Array.from(tr.cells).sort((a, b) => {
        const textA = parseFloat(a.textContent);
        const textB = parseFloat(b.textContent);
        return textB - textA;
    });
    const cellsLength = sortedCells.length; // Use sortedCells.length here
    for (let i = 0; i < cellsLength; i++) {
        const cell = sortedCells[i]; // Iterate over sortedCells
        tr.replaceChild(cell, tr.cells[i]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search