How to get the parentNote under DOM?

C

Cylix

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?

Thanks
 
R

RobG

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top