Samik Sengupta Samik Sengupta - 1 month ago 13
Javascript Question

How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery

<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>


Goal: To get buttons
button1
and
button2
to trigger the same
function get()
which should get the value of the first
<td>
in the same
<tr>
the button resides in. Which is, in this case:
foo1
and
foo2
respectively.

This is a rough outline of the function which should help understand what I'm trying to achieve-

function get(element){
alert(element.tr.first_td.innerHTML);
}


I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.

Answer

Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:

function find( element ) {
    alert( element.parentNode.parentNode.cells[0].innerHTML );
}‚Äč

Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/