Reputation: 73
I have an HTML table to traverse using DOM. I begin accessing using my table id and then I am able to access a particular cell.
'<td><a onclick=send_symbol_2(\"'+comp+'\")>'+comp+'</a></td>'
I am confused on how to access the data contained within anchor tags. I had earlier constructed the table by adding strings.
eg: '<tr></td><td>'+arr[4]+'</td></tr>'
I understand toString() would been called.
I am unsure how to proceed further.
I used
rows[i].getElementsByTagName("td")[0]
to access the cell data.
Upvotes: 0
Views: 2288
Reputation: 148
Try This :
var tableObj = document.getElementById("testTable");
var rows = tableObj.getElementsByTagName("tr");
for(var i=0; i< rows.length ; i++){
var cells = rows[i].getElementsByTagName("td");
for (var j=0; j<cells.length ; j++) {
console.log(cells[j].innerText);
}
}
<table id="testTable">
<tr>
<td>1</td><td>2</td>
</tr>
<tr>
<td>3</td><td>4</td>
</tr>
</table>
Upvotes: 1
Reputation: 20734
Let's say we have such a table
<table id="table">
<tr><td>11</td><td>12</td></tr>
<tr><td>21</td><td>22</td></tr>
</table>
Then to access some specific cell content I would use the following approach:
function getCellContent(x, y) {
x = parseInt(x, 10);
y = parseInt(y, 10);
if(isNaN(x) || --x < 0 || isNaN(y) || --y < 0) {
return;
}
var tE = document.getElementById('table');
var rows = tE.getElementsByTagName('tr');
if(!rows || y >= rows.length) {
return;
}
var row = rows[y];
var cells = row.getElementsByTagName('td');
if(!cells || x >= cells.length) {
return;
}
var cell = cells[x];
return cell.innerHTML;
}
console.log(getCellContent(1, 2)); // "12"
Note, that x
, y
arguments are being started from "1". That's why I decrementing arguments. Three return
statements are for bad params and out-of-range protections. So you'll get just undefined
if something's not ok.
I also created a Plunker demo.
Upvotes: 1