I am attempting to employ simple tables that my client can use to supply info to her website. I would like to read the table from an HTML page and transfer the tabular data to an array for manipulation.
any idea?
geo.
any idea?
geo.
function tableData(T){
if(!T) T= document.getElementsByTagName('table')[0];
if(!T || !T.nodeName || /table/i.test(T.nodeName)==false){
throw new Error('No table found');
}
var A= [];
var h= T.getElementsByTagName('thead');
var f= T.getElementsByTagName('tfoot');
var r= T.getElementsByTagName('tr');
var Lh= h.length;
var Lf= f.length;
var Lr= r.length;
if(Lh) A.push(h[0]);
while(Lr) A.push(r[--Lr]);
if(Lf) A.push(f[0]);
var L=A.length;
var B, row, c, c2, Lc, cell, tem;
for(var i=0; i<L; i++){
B= new Array();
row= A[i];
c= row.getElementsByTagName('th');
c2= row.getElementsByTagName('td');
Lc= c.length;
Lc2= c2.length;
while(Lc){
cell= c[--Lc];
temp= deepText(cell);
B.push(temp);
}
while(Lc2){
cell=c2[--Lc2];
temp= deepText(cell);
B.push(temp);
}
A[i]=B;
}
return A;
}
function deepText(who){
var tmp= '', tex, cnt= 0;
var pa= who.childNodes;
while (pa && pa[cnt]){
tex= pa[cnt++];
if(tex.nodeType=== 3 && tex.data) tmp+= ' '+ tex.data;
else if(tex.hasChildNodes()) tmp+= deepText(tex);
}
return tmp;
}
function dataString(A){
var L=A.length;
var temp=[], tem;
for(var i=0;i<L;i++){
tem=A[i].join('\t\|\t');
temp.push((i+1)+'. '+tem);
}
return temp.join('\n');
}
var A=tableData();
var S=dataString(A); // 2 dimensional array to string
alert(dataString(A)) // data dump
Comment