Getting an nth-child parent

I have a table where I need the first two cells of each row that can be clicked (NOT the entire row). When I click the first or seccond cell, I want to get the value of the third cell of the same row. To clarify when I press a1 , I want the warning to show c1 . If I press b2 , I want it to show c2 , and if I press c3 , I do not want something to happen.

As you can see, my alert($(this).parent(':nth-child(3)').text()); does not work. How can i achieve this?

 $('td:nth-child(-n+2)').on("click", function(){ alert($(this).parent(':nth-child(3)').text()); //Doesn't work }); 
 td{ border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table> <tr> <td>a1</td> <td>b1</td> <td>c1</td> </tr> <tr> <td>a2</td> <td>b2</td> <td>c2</td> </tr> <tr> <td>a3</td> <td>b3</td> <td>c3</td> </tr> </table> 
+6
source share
4 answers

you need to use .closest('tr') .. to select parent tr and .find() to select td:nth-child(3)

 $('td:nth-child(-n+2)').on("click", function(){ alert($(this).closest('tr').find('td:nth-child(3)').text()); }); 

Working demo

+7
source

you can use

 $('td:lt(2)').on("click", function () { alert($(this).parent().find("td:eq(2)").text()); //Doesn't work }); 

Fiddle

  • lt(2) will receive the indicated elements whose index is less than 2
  • eq(2) selects an element whose index is 2
+4
source

Use this

 $(this).parent().children(':nth-child(3)').text() 

Select the parent and then its child.

Jsfiddle

+3
source

This work for me:

 $('table tr').each(function(){ $(this).find('td:lt(2)').on("click", function () { var text = $(this).parent().find("td:eq(2)").text(); console.log(text); }); }); 
0
source

All Articles