Cylix said:
I have a <span onclick="clickMe()">Click Me</span> on the
table.rows[2].cells[2]
How can clcikMe can show the name of the table, row col it contains?
A table element doesn't have a name attribute, use ID instead.
A cell has a cellIndex property and it's always a child of a TR, so its
parentNode is the row it belongs to. The row number is held in the
row's rowIndex property.
Rows always belong to a table section element (tbody, tfoot or thead),
so the TR's parent node will be the table section it belongs to. And
finally, a table section element always belongs to a table element.
So if your onclick handler passes 'this':
<span onclick="clickMe(this)">Click Me</span>
your function should be something like:
function clickMe(el){
// Find the td parent of the clicked-on node
while (el.nodeName.toLowerCase() != 'td' && el.parentNode){
el = el.parentNode;
}
// Make sure you found a td
if (el.nodeName.toLowerCase() != 'td'){
return; // maybe return something to show it failed
}
var row = el.parentNode;
var table = row.parentNode.parentNode;
alert('Cell index: ' + el.cellIndex
+ '\nRow index: ' + row.rowIndex
+ '\nTable id: ' + ((table.id)? table.id : 'no id')
);
}
And some play HTML:
<table id="aTable">
<tr>
<td></td>
<td><span onclick="clickMe(this)">Click Me</span></td>
</tr>
</table>