| re: How to get the data of a table from the first to the last row with a JavaScript
Stefan Mueller wrote:[color=blue]
> I have a table dynamically created with a JavaScript (insertRow, deleteRow).
> At the end I'd like to go through the whole table (beginning at the first
> and ending at the last row) to display all the data e.g. with alert().
> Is there an easy way to go through the whole table to read the data (each
> row has an unique ID but I don't know their IDs) or do I need while
> modifying the table to rememder each row's ID so I can access to data
> directly with their IDs?[/color]
Presumably you have a reference to the table. I'm not sure it's wise to
blast it all into an alert, there's a good chance you can't see it all.
The following just requires a reference to the table, nothing more (oh,
and support for the rows and cells collections):
function showTableContent(theTable)
{
var content=[];
var row, cell;
if (!theTable.rows || !theTable.rows[0].cells) return;
for (var i=0, rlen=theTable.rows.length; i<rlen; ++i){
row = theTable.rows[i];
for (var j=0, clen=row.cells.length; j<clen; ++j){
content.push('row ' + i +' cell ' + j + ': '
+ getElText(row.cells[j]));
}
}
alert(content.join('\n'));
}
function getElText(el)
{
if (el.textContent) return el.textContent;
if (el.innerText) return el.innerText;
var x = el.childNodes;
var txt = '';
for (var i=0, len=x.length; i<len; ++i){
if (3 == x[i].nodeType) {
txt += x[i].data;
} else if (1 == x[i].nodeType){
txt += getElText(x[i]);
}
}
return txt.replace(/\s+/g,' ');
}
--
Rob |