get the next row in a table-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.getElement开发者_如何学运维sByTagName("td");
alert(column[0].innerText);
//now i want to move to the next row...something like row=row.next()?????
}
}
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.
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.
Try using the nextSibling
property:
row = row.nextSibling
But note that whitespace in your source HTML may turn into text nodes among the rows. You may have to call nextSibling
more than once to skip the text nodes.
Have you considered using jQuery? With jQuery, you don't have to worry about the text nodes:
row = $("#" + rowId);
...
row = row.next();
row = row.nextSibling
. You might need to do that in a while loop as you may come across whitespace nodes, so you should check to see if the next node has the correct tagName.
If you can use jQuery, then it's becoming really easy.
row.next();
Use document.getElementById(rowId).nextSibling
精彩评论