Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting nth-child of parent

I have a table where I need the first two cells of every row clickable (NOT the entire row). When I click the first or the seccond cell, I want to get the value of the third cell of that same row. To clarify, when I press a1 I want the alert to show c1, If I press b2 I want it to show c2 and If I press c3 I dont want anything to happen.

As you can see, my alert($(this).parent(':nth-child(3)').text()); doesn't 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>
like image 301
Johan Hjalmarsson Avatar asked Dec 01 '15 12:12

Johan Hjalmarsson


2 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

like image 69
Mohamed-Yousef Avatar answered Sep 19 '22 23:09

Mohamed-Yousef


Use this

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

Select the parent and then a child of it.

JsFiddle

like image 43
Schneyer Avatar answered Sep 19 '22 23:09

Schneyer