Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearranging table in JavaScript

Tags:

javascript

I want reorder table rows using JavaScript .

for example take the following dummy table:

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td>A1</td>
    <td>B1</td>
    <td>C1</td>
    <td>D1</td>
  </tr>
</table>

I want to do this in JavaScript without using jQuery. I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row.

I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?

like image 659
Ben Avatar asked Apr 29 '09 03:04

Ben


Video Answer


2 Answers

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.

like image 114
Rex M Avatar answered Oct 10 '22 12:10

Rex M


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);
like image 22
levik Avatar answered Oct 10 '22 11:10

levik