Rearranging table in JavaScript

If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it:

<table id="mytable">
...
</table>

<script type="text/javascript">
    var tbl = document.getElementById('mytable');
    var rows = tbl.getElementsByTagName('tr');
    var firstRow = rows[0];
    var lastRow = rows[rows.length];
    firstRow.parentNode.insertBefore(lastRow.parentNode.removeChild(lastRow), firstRow);
</script>

Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.


The best way to solve this in Javascript is:

Give the Tr.. a unique name. for eg: X_Y,X_Z,A_Y,A_Z

Now add a hidden lable or text Box which gives the sorting order from the server i.e When the page renders I want to sort it All the Tr's that have a ID starting with A should come first and All the Z's should come second.

<asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X</label>
<asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y</label>

When the page renders..the order should be A_Z,A_Y,X_Z,X_Y

Before Rendering this is table that comes from the aspx file:

<table>
<tr id='Tr_Heading'>
  <td>A</td>
  <td>B</td>
</tr>
<tr id="Tr_X_Y">
  <td>GH</td>
  <td>GH1</td>
</tr>
<tr id="tr_X_Z">
  <td>HU</td>
  <td>HU1</td>
</tr>
<tr id="tr_A_Z">
  <td>JI</td>
  <td>JI1</td>
</tr>
<tr id="tr_A_Y">
  <td>JI</td>
  <td>JI1</td>
</tr>

Script:

function SortAndArrange()
{
var firstList = document.getElementById('lblFirstSortOrder').value;
var secondList = document.getElementById('lblSecondSortOrder').value;
var firstTypes = new Array();
firstTypes = firstList.split(',');
var secondLists = new Array();
secondLists = secondList.split(',');
var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]);
for (var i = 0; i<firstTypes.length; i++)
{
  for (var j = 0; j< secondTypes.length;j++)
  {
     var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j];
     var FirstSecondTrs = document.getElementById(TrName);
     if (FirstSecondTrs)
     {
       FirstSecondTrs.parentNode.removeChild(FirstSecondTrs);        
       insertAfter(refNode,FirstSecondTrs);
       refNode = FirstSecondTrs;
     }
  }
 }
}
function insertAfter( referenceNode, newNode )
{   
 referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page...

Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution.

Thanks, Ben


Do:

var table = ...; // Get reference to table (by ID or other means)
var lastRow = table.rows[table.rows.length - 1];
lastRow.parent.insertBefore(table.rows[0], lastRow);

Tags:

Javascript