Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the next row in a table-javascript

Tags:

javascript

how wud u get the next row in the following example? (i am trying to print the next three row/column values of the rowId provided)

function printRowData(rowId)
{
    var row=document.getElementById(rowId);
    for(i=0; i<3 ; i++)
    {
        var column=row.getElementsByTagName("td");
        alert(column[0].innerText);

        //now i want to move to the next row...something like row=row.next()?????
     }

}
like image 401
samach Avatar asked Jul 05 '11 13:07

samach


2 Answers

If you just want the next row, and not subsequent rows, you can do this:

var next = row.parentNode.rows[ row.rowIndex + 1 ];

So your code could look like this:

function printRowData(rowId) {
    var row=document.getElementById(rowId);
    var idx = row.rowIndex;
    for(i=0; i<4 ; i++) {
        if( row ) {
            alert(row.cells[0].innerText);
           var row = row.parentNode.rows[ ++idx ];
        }
    }
}

From the current row, it gets the .parentNode, then from that, it accesses the rows collection, and increments the .rowIndex property of the original row to select the next.

This takes care of white space issues.

Notice also that instead of getElementsByTagName, I replaced it with row.cells, which is a collection of the cells in the row.


EDIT: Forgot to include the rows property after parentNode. It was included in the description though. Fixed.

like image 154
user113716 Avatar answered Oct 09 '22 22:10

user113716


To get around the problems with whitespace you can now use

row = row.nextElementSibling

Just make sure to check for null when you get to the end of the table, or if you have a thead, tbody or tfoot it will be at the end of that particular node.

If you're supporting older browsers you may want to use a shim.

like image 38
Matt McCabe Avatar answered Oct 09 '22 21:10

Matt McCabe