I’m doing some manipulation and retrieval of values stored in a table.
Each row contains record where each column represents a property of that record. Much like how you typically think of a database table.
So my first question is: Is it a safe/acceptable/portable practice to access elements in the row using known childNodes[] indices of the row?
Given this example table:
<table id='sometable'>
<thead><tr><th>Name</th> <th>Age</th></tr></thead>
<tbody>
<tr><td>Bob</td><td>25</td></tr>
<tr><td>Alice</td><td>31</td></tr>
</tbody>
</table>
Is it ok to do things like this?
/* Get just the 'tbody' rows, i.e. not the header row */
function getTableBodyRows(tblName){
return document.getElementById(tblName).getElementsByTagName('tbody')[0].getElementsByTagName('tr');
}
/* Get the 'name' value for each row */
function getNames( ){
var rows = getTableBodyRows('sometable');
var names = [];
for( var i=0; i < rows.length; i++ ){
/* This line assumes childNode[0] of the row is the 'name' cell (td) which
contains only a single text node. */
names.push( rows[i].childNodes[0].childNodes[0].nodeValue);
}
return names;
}
Aside from the fact that I would probably define a value to represent the column numbers instead of using literal is there anything wrong with this approach?
One alternative I thought of would be to add a class attribute to each <td> to identify the content of the cell, and then use a getElementsByClassName() method to retrieve individual values, but it seems like performance would take a significant hit for large tables. And result in writing more code for little benefit.
Are there other common techniques for accomplishing the tasks like “get the ‘name’ value from table row ‘x'”?
I should also note that I am generating my tables with javascript so I don’t think I have to worry about the issue of how different browsers may or may not consider whitespace a childNode.
If by elements, you mean just the cells, then no. You should use the
.cellsproperty of the row to avoid potential whitespace between cells.I’d update your code like this:
Notice that I’ve also used the
.tBodiesproperty of thetable, and the.rowsproperty of thetbody.You can also use the
.rowsproperty directly on thetableto get all rows in the table.I missed your last sentence about whitespace, but I’d still use the built-in collections that tables provide instead of DOM selection methods.
No sense in building new collections when they’re right there waiting for you. 😉
While
childNodeswould work when there’s no whitespace, it would be a better habit to use.cells.