views:

215

answers:

3

I am trying to get the text value of a table cell relative to a clicked link. Click the link in any of the cells of class 'three" and get the text of that particular row's cell named class 'one'.

<tr>
<td class='one'><a href="#">Text to get</a></td>
<td class='two'>meh</td>
<td class='three'><a href="#">Click this to get the text in the first cell of this row</a></td>
</tr>
<tr>
<td class='one'>Different text to get</td>
<td class='two'>blah</td>
<td class='three'><a href="#">Click this to get the text in the first cell of this row</a></td>
</tr>

I can get the clicked element's text with something like:

console.log($(this).text());

But how do I get the text of that first cell in the row?

I thought that, as an example, it would be somethng like:

console.log($(this).prev().prev().text());

But that is not correct (returns "an empty string"). Any suggestions?

+2  A: 

Try:

$(this).closest('td').siblings('.one').text();

CalebD
Bam... instant solution. Thanks CalebD.
gaoshan88
+1  A: 
$("td.three a").click(function(e){
  e.preventDefault();
  var myText = $(this).closest("tr").find("td.one").text();
});
Jonathan Sampson
+1  A: 

would this work?

http://jsbin.com/opafa

$('td.three a').click(function(e) {
    e.preventDefault();

    var txt = $(this).prevAll('.one').text();

    alert(txt);
});
Jon Erickson