By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,970 Members | 1,669 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,970 IT Pros & Developers. It's quick & easy.

How to get the parentNote under DOM?

P: n/a
I have a <span onclick="clickMe()">Click Me</spanon the
table.rows[2].cells[2]

How can clcikMe can show the name of the table, row col it contains?

Thanks

Jul 21 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Cylix wrote:
I have a <span onclick="clickMe()">Click Me</spanon 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>
--
Rob

Jul 21 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.